Have this JSON:
Online viewable at: http://www.jsoneditoronline.org/?id=97bbcb19871e89ff0702f8547589a688
Trying to parse it out, but some fields names are dates, so I am not sure how to do it.
I want to parse and store in DB (persist in MongoDB):
- date
- reference (neo_reference_id)
- name
- speed (kilometers_per_hour)
- is hazardous (is_potentially_hazardous_asteroid)
Trying to do it like this, so I can get reference, name, speed and is hazardous:
$data = json_decode($response->getBody(), true);
foreach($data['near_earth_objects'] as $neos)
{
foreach($neos as $item)
{
$output->write($item['name']);
}
}
How to get the date field correspondingly?
What is the best practice to parse JSON data in Symfony2?
Thanks,
Update 1:
Tried as Half Crazed has answered:
$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);
}
}
$date is there, but in the second look it make a warning and nothing gets displayed.
[Symfony\Component\Debug\Exception\ContextErrorException]
Warning: Invalid argument supplied for foreach()
Any tips?
Thanks,
Update 2:
This does it.
Can it be improved for better performance and code readability :) ?
$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;
}
}
}
}
}