foreach循环遍历json值

时间:2018-10-24 19:07:05

标签: php json foreach

我从URL获得json结果:

{
        "result": [{
            "user.name": "Spider Man",
            "user": "a4ac7bfe6f581640a62d3c31be3ee4dc"
        }, {
            "user.name": "Bat Man",
            "user": "af406b85e4b13500b95fa1eeac1ce626"
        }, {
            "user.name": "Iron Man",
            "user": "18ed9aba4ffb07006979ab6ba110c757"
        }, {
            "user.name": "Ant Man",
            "user": "877a503a98cc4200b95f526ea1ece471"
        }, {
            "user.name": "Captain America",
            "user": "8ec0d9634f2f22004b19ca1f0310c791"
        }]
    }

如何创建foreach循环以获取以下输出:

Spider Man
Bat Man
Iron Man
Ant Man
Captain America

与json中的用户值相同。

我尝试了以下代码,但无法弄清楚:

$json = file_get_contents($queryURL, false, $context) or die ("keine verbindung");
$array = json_decode($json, true);
foreach($array as $data) {
    $data->user;
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您解码为数组而不是对象。此外,还有另一个级别result

foreach($array['result'] as $data) {
    echo $data['user'];
}