有此JSON:Symfony2的Json的解析與日期
在線觀看: http://www.jsoneditoronline.org/?id=97bbcb19871e89ff0702f8547589a688
試圖解析出來,但有些字段名是日期,所以我不知道該怎麼做。
我想分析並存儲在數據庫(MongoDB中仍然存在):
- 日期
- 引用(neo_reference_id)
- 名
- 速度(kilometers_per_hour)
- 是危險的(is_potentially_hazardous_asteroid )
試着d所以我可以獲得參考,名稱,速度和危險性:
$data = json_decode($response->getBody(), true);
foreach($data['near_earth_objects'] as $neos)
{
foreach($neos as $item)
{
$output->write($item['name']);
}
}
如何獲取相應的日期字段?
在Symfony2中解析JSON數據的最佳實踐是什麼?
感謝,
更新1:
嘗試作爲半瘋狂已經回答了:
$jd = new JsonDecode();
$neo_obj = $jd->decode($response->getBody(),"json");
foreach($neo_obj->near_earth_objects as $date => $object) {
// store $date here
$output->write($date);
foreach($date as $objects) {
$links = $objects['links'];
$neo_ref_id = $objects['neo_reference_id'];
$output->write($links);
$output->write($neo_ref_id);
}
}
$日期是存在的,但在第二次看它做出警告,並沒有得到顯示。
[Symfony\Component\Debug\Exception\ContextErrorException]
Warning: Invalid argument supplied for foreach()
任何提示?
感謝,
更新2:
該做的。
可以改進以獲得更好的性能和代碼可讀性:)?
$jd = new JsonDecode();
$neo_obj = $jd->decode($response->getBody(),"json");
foreach($neo_obj->near_earth_objects as $date => $object) {
$output->writeln("date:".$date);
foreach($neo_obj->near_earth_objects as $object1) {
foreach($object1 as $object2)
{
$output->writeln("name:".$object2->name);
$output->writeln("neo_reference_id:".$object2->neo_reference_id);
$output->writeln("is_potentially_hazardous_asteroid:".$object2->is_potentially_hazardous_asteroid);
foreach($object2->close_approach_data as $object3)
{
$i=0;
foreach($object3->relative_velocity as $object4)
{
if($i===1)
{
$output->writeln("speed:".$object4);
}
$i=$i+1;
}
}
}
}
}
Thanks @Half Crazed !!!根據您的建議,我更新了Update 1的問題。不幸的是,第二個循環存在問題。有任何想法嗎? –
想通了。你能看到我的更新2,也許建議改進? –
@android_dev你不需要做foreach($ neo_obj-> near_earth_objects as [...]){'兩次。您可以刪除內部的'foreach',而是仍然在'$ object'上循環。 '$ object'將成爲'near_earth_objects [date]'數組中的所有內容。如果你不確定是否應該訪問一個數組項或對象屬性,例如'$ array ['key']'vs'$ obj-> prop',那麼你應該隨時'var_dump($ var) –