通过PHP循环使用JSON来获取子项

时间:2015-06-01 10:19:23

标签: php json foreach children

我整个上午一直在努力做一些看起来非常简单的事情而且我的失败是悲惨的。

我有一个API请求,它返回有效的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为$ 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";
    }

}

我需要能够返回以下节点....

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

我完全卡住了!

var_dump会返回我的数组,因此cURL现在正常工作。

西蒙

1 个答案:

答案 0 :(得分:1)

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

来自PHP curl_exec page

  

成功时返回TRUE ,失败时返回FALSE。但是,如果设置了CURLOPT_RETURNTRANSFER选项,它将在成功时返回结果,在失败时返回FALSE。

它取得了成功,但你没有告诉它你期待一个回应,所以它会返回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访问该内容。

在你的第二次预告中,你试图访问一个物体的属性。结果不是一个对象,它是一个数组(看看你的JSON,它包含一个[,所以它是一个数组)。要获得费率,请遵循JSON字符串,您将看到您需要执行此操作:

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