MVC - 在PHP中通过更大的JSON数据集进行处理

时间:2016-11-09 16:08:12

标签: php json

我正在使用PHP脚本循环一个更大的JSON数据集,其结构如下:

"_embedded":{  
   "keyword":[  
      {  
         "_id":{  
            "$id":"570f7769767e582d008b511e"
         },
         "labels":[  
            {  
               "label":"Sample label",
               "category":"sample label category",
               "sport":"sample sport",
               "project":"core"
            }
         ]
      },
      {  
         "_id":{  
            "$id":"570f77c8f2c2ce20008b5108"
         },
         "labels":[  
            {  
               "label":"Sample label 2",
               "category":"sample label category 2",
               "sport":"sample sport 2",
               "project":"core"
            }
         ]
      }
   ]
}

这是我在PHP中的脚本

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);

$keywords = array();
$data = json_decode($result, true); // ASSOCIATIVE ARRAY

foreach($data["_embedded"]["keyword"] as $dataitem) {
    // GRAB NECESSARY MVC ITEMS
    $identifier = $dataitem->_id->$id;
    $label = $dataitem->labels[0]->label;

    // ADD TO KEYWORDS RESPONSE
    $keywords[] = array("id" => "$identifier", "label" => "$label");
}

$output = json_encode($keywords);
header('Content-Type: application/json');
echo $output;

我的问题在我的foreach循环中,因为我输出了相应的JSON结构,但值全部为空,如下所示:

{
   "id": "",
   "label": ""
},
{
   "id": "",
   "label": ""
},

2 个答案:

答案 0 :(得分:0)

您正在将其作为对象访问,但它的数组。 试试:

 $identifier = $dataitem['_id']['$id'];
 $label = $dataitem['labels'][0]['label'];

答案 1 :(得分:0)

尝试使用数组访问数据,因为json中的数据将作为数组出现。

 $identifier  = $dataitem['_id']['$id'];
 $label = $dataitem['labels'][0]['label'];