需要一个项目列表,但得到类型“dict”PHP

问题描述 投票:0回答:1

我正在连接到 API,并在传递以下数据格式时收到此错误:

 $data = array(
            "from_date" => "2021-11-10",
            "to_date" => "2021-11-21",
            "adults" => 1,
            "guest_id" => 2954339,
            "stay_type" => "GUEST",
            "entities" => [ "property_id" => 89835 ]
        );
        $reservation = fetch_api('reservations', '', 'POST', $data);

错误:

 [message] => Expected a list of items but got type "dict".
 [code] => not_a_list

问题在于

entities
值。我相信这是因为它是一个数组。下面是我的
fetch_api
函数。当连接到其他端点并发送没有嵌套数组的数据时,它可以正常工作。

function fetch_api($endpoint, $parameters = '', $method = 'GET', $data = null){
        $curl = curl_init();
        $headers = array(
            "accept: application/json",
            "Authorization: Token xxxxxx",
            "cache-control: no-cache",
            "content-type: application/json",
        );
        if ($method == 'GET') {
            curl_setopt($curl, CURLOPT_HTTPGET, 1);
        }

        if ($method == 'POST') {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
        }
        
        curl_setopt($curl, CURLOPT_URL, 'https://www.lodgix.com/public-api/v2/'. $endpoint .'/' . $parameters);
        

        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        $result = curl_exec($curl);
        $result = json_decode($result);
        if (!$result) {
            die("Connection Failure");
        }
        curl_close($curl);
        return $result;
    }

我尝试过

json_encode
嵌套数组,如下所示:

if ($method == 'POST') {
            curl_setopt($curl, CURLOPT_POST, 1);
    
            if ($data) {
                for ($i=0; $i < count($data); $i++) { 
                    if (gettype($data[$i]) === 'array') {
                        json_encode($data[$i]);
                    }
                }
            }
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
        }

不幸的是,这没有帮助。我是否相信问题出在嵌套数组上,或者问题完全不同?

php curl
1个回答
0
投票

根据我的经验,当使用 json_encode 和产生此类错误的服务器所需的 json 结构时,两个数组中需要列表数据,例如:

$data = array(
    "from_date" => "2021-11-10",
    "to_date" => "2021-11-21",
    "adults" => 1,
    "guest_id" => 2954339,
    "stay_type" => "GUEST",
    "entities" => [[ "property_id" => 89835 ]]
);
$reservation = fetch_api('reservations', '', 'POST', $data);
© www.soinside.com 2019 - 2024. All rights reserved.