将每个数组的JSON解码为PHP

时间:2016-11-30 07:45:57

标签: php json

我有一些像这样编码的json:

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

我想将JSON解码为PHP输出,如:

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

我尝试了这个但是没有工作:

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

3 个答案:

答案 0 :(得分:3)

尝试将foreach循环更改为此。

foreach ($list as $key => $value) {
        echo $value->title."  ||  ";
        echo $value->link." ";
        echo nl2br("\n");
        }

希望这对你有用。

答案 1 :(得分:0)

你所做的是循环键和值分离,而你试图从stdClass的键中获取值,你需要做的是将它作为一个对象循环。我还使用json_decode($json_str, true)将结果作为数组而不是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'];
}

答案 2 :(得分:0)

代码:

$list = json_decode($json);
foreach ($list as $item) {
    echo $item->title . ' || ' . $item->link . '<br>';
}