I am having a php function that returns a JSON object.
Running this code:
$obj = json_decode($result); print_r($obj);
where $result
is the output of the function. The $result
is:
{"result":[{"name":"name1","title":"title1","type":"1","place":"place1"},
{"name":"name2","title":"title2","type":"1","place":"place2"}]}
My output is this:
stdClass Object ( [result] => Array ( [0] => stdClass Object ( [name] => name1 [title] => title1 [type] => 1 [place] => place1 )
[1] => stdClass Object ( [name] => name2 [title] => title2 [type] => 1 [place] => place2 ) ))
So what I want is to access the name1,title1 and so on value for each of the items.
I tried this:
echo $obj->result[0];
for getting the first row, but it gives me nothing.
If I try something like this:
foreach ($obj as $key => $value) {
var_dump ($value);
foreach ($value as $feature => $item) {
echo $feature.' =>' .$item;
}
}
It enter the first loop only once (output is an array(2) and the items) and it does not enter the second for loop at all. I know that it has something to do with the arrays and the JSON objects but I cannot make it work.
Any help?
Try this instead:
$json = json_decode($json);
foreach($json->result as $index => $item) {
// $item is an object now, you can access $item->name, $item->title, etc.
}
If you want to loop over each key inside that, you can do a foreach on $item with $key => $value;
$obj->result[0]
is an object; that's why echo
isn't working. Try this: echo $obj->result[0]->name;
If you want to print the name , you can probably try this
echo $obj->result[0]->name; // which should dereference the appropriate object.
Also in the loop, try this as $obj->result is the array and $obj is a single object
if($obj && isset($obj->result) && is_array($obj->result)){
foreach ($obj->result as $key => $value) {
var_dump ($value);
foreach ($value as $feature => $item) {
echo $feature.' =>' .$item;
}
}
}