dennis ramli dennis ramli - 7 days ago 5
JSON Question

decode json each array to php

i have some encoded json like this

[
{"title":"root","link":"one"},
{"title":"branch","link":"two"},
{"title":"leaf","link":"three"}
]


i want to decode that json into php output like

title || link
root || one
branch || two
leaf || three


i tried this but doesn't work

$list = json_decode($json);
foreach ($list as $list => $value) {
echo $list->title;
echo $list->link;
}

Answer

What you did is looping the keys and values seperated and than you tried to get the values from the keys of the stdClass, what you need to do is looping it as an object. I also used json_decode($json_str, true) to get the result as an array instead of an stdClass.

$json_str = '[{"title":"root","link":"one"},{"title":"branch","link":"two"},{"title":"leaf","link":"three"}]';
$json_decoded = json_decode($json_str, true);
foreach($json_decoded as $object)
{
    echo $object['title'];
    echo $object['link'];
}