用 PHP 遍历 JSON 得到 children

Looping through JSON with PHP to get children

我整个上午都在尝试做一些看起来很简单的事情,但我失败得很惨。

我有一个 API 请求,其中 return 是有效的 JSON 数据,我需要遍历 PHP 中的各种值,以便将多个节点放入我的应用程序.

这是 JSON

的片段
{
"results": [
    {
        "date": "2015-06-01",
        "rates": [
            {
                "id": 1592,
                "name": "Weekend promotion",
                "room_rates": [
                    {
                        "room_type_id": 66,
                        "room_type_code": "DLK",
                        "sold": 0,
                        "sell_limit": null,
                        "availability": 25,
                        "out_of_order": 0,
                        "single": 85,
                        "double": 85,
                        "extra_adult": null,
                        "child": null
                    },
                    {
                        "room_type_id": 90,
                        "room_type_code": "DLT",
                        "sold": 0,
                        "sell_limit": null,
                        "availability": 11,
                        "out_of_order": 0,
                        "single": 85,
                        "double": 85,
                        "extra_adult": null,
                        "child": null
                    },

这就是我想要做的,但我不断收到以下错误(已编辑以更新 cURL 响应):

Notice: Trying to get property of non-object in /vagrant/web/web/bookingStep2.php on line 135

Warning: Invalid argument supplied for foreach() in /vagrant/web/web/bookingStep2.php on line 135

Notice: Trying to get property of non-object in /vagrant/web/web/bookingStep2.php on line 135

Warning: Invalid argument supplied for foreach() in /vagrant/web/web/bookingStep2.php on line 135

知道我做错了什么吗?第135行是这样的:

foreach($responseData as $mydata)

$url = 'https://myapi.com/availability?token=xx&from_date='.$from_date.'&to_date='.$to_date;

$options = array(
    CURLOPT_RETURNTRANSFER => true,   // return web page
    CURLOPT_HEADER         => false,  // don't return headers
    CURLOPT_FOLLOWLOCATION => true,   // follow redirects
    CURLOPT_MAXREDIRS      => 10,     // stop after 10 redirects
    CURLOPT_ENCODING       => "",     // handle compressed
    CURLOPT_USERAGENT      => "test", // name of client
    CURLOPT_AUTOREFERER    => true,   // set referrer on redirect
    CURLOPT_CONNECTTIMEOUT => 120,    // time-out on connect
    CURLOPT_TIMEOUT        => 120,    // time-out on response
); 
$ch = curl_init($url);
curl_setopt_array($ch, $options);
$result = curl_exec($ch);

curl_close($ch);


// Decode the response
$responseData = json_decode($result, TRUE);

// Put everyting to the screen with var_dump;
var_dump($responseData);

// With print_r ( useful for arrays );
//print_r($responseData);

// List just review ratings with foreach;
foreach($responseData as $mydata)
{
    foreach($mydata->results as $values) {
        echo $values->rates . "\n";
    }

}

我需要能够 return 以下节点....

results>rates>name
results>rates>room_rates>room_type_id
results>rates>room_rates>availability

我完全卡住了!

var_dump 执行 return 我的数组,因此 cURL 现在可以正常工作。

西蒙

看起来你的 cURL 请求是罪魁祸首,你没有告诉 cURL 你期待一个响应,所以 cURL 只是为你的初始请求传回一个布尔值成功,它发送成功。

来自PHP curl_exec page.

Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.

它成功了,但你并没有告诉它你期待一个回应,所以它 returns TRUE.

试试这个:

$url = 'https://myapi.com/api?token=xxx&from_date='.$from_date.'&to_date='.$to_date;

$options = array(
    CURLOPT_RETURNTRANSFER => true,   // return web page <-- This is the important one that tells cURL you want a response.
    CURLOPT_HEADER         => false,  // don't return headers
    CURLOPT_FOLLOWLOCATION => true,   // follow redirects
    CURLOPT_MAXREDIRS      => 10,     // stop after 10 redirects
    CURLOPT_AUTOREFERER    => true,   // set referrer on redirect
    CURLOPT_CONNECTTIMEOUT => 120,    // time-out on connect
    CURLOPT_TIMEOUT        => 120,    // time-out on response
); 
$ch = curl_init($url);
curl_setopt_array($ch, $options);
$result = curl_exec($ch);

curl_close($ch);

第二个错误

现在我们已经让 cURL 工作了,让我们来处理结果。请记住,当转换 JSON 时,每个大括号 ({) 将生成一个对象,而每个方括号 ([) 将生成一个数组。因此,如果我们按照您的 JSON 进行操作,我们可以看到您将得到一个包含 属性 results 的对象。您可以使用 $responseData->results.

访问它

在您的第二个 foreach 中,您试图访问一个对象的 属性。结果不是一个对象,它是一个数组(看看你的 JSON,它包含一个 [,所以它是一个数组)。要通过 JSON 字符串获取费率,您会发现您需要这样做:

foreach($responseData->results[0]->rates as $rate) {
    echo $rate->id . "\n";
}