I have a JSON data like this:
{
"hello":
{
"first":"firstvalue",
"second":"secondvalue"
},
"hello2":
{
"first2":"firstvalue2",
"second2":"secondvalue2"
}
}
I know how to retrieve data from object “first” (firstvalue) and second (secondvalue) but I would like to loop trough this object and as a result get values: “hello” and “hello2″…
This is my PHP code:
<?php
$jsonData='{"hello":{"first":"firstvalue","second":"secondvalue"},"hello2":{"first2":"firstvalue2","second2":"secondvalue2"}}';
$jsonData=stripslashes($jsonData);
$obj = json_decode($jsonData);
echo $obj->{"hello"}->{"first"}; //result: "firstvalue"
?>
Can it be done?
The JSON, after being decoded, should get you this kind of object :
(You can use
var_dump($obj);to get that)i.e. you’re getting an object, with
helloandhello2as properties names.Which means this code :
Will get you :
This will work because [`foreach`][1] can be used to iterate over the properties of an object — see [Object Iteration][2], about that.