简体   繁体   English

PHP echo json 与键值

[英]PHP echo json with key value

why does this code not work correctly or what am I doing incorrectly?为什么这段代码不能正常工作或者我做错了什么?

$json = json_encode($myInstance->getData($id));
    $result = json_decode($json,true);
    $i = 0;
    foreach ($result as $value) {
        echo '<div>'.$value[$i]['name'].'</div>';
        $i++;
    }

The first value is shown correctly but it doesn't iterate through!第一个值显示正确,但没有迭代! Is $value[$i]['name'] not build for iterating?? $value[$i]['name']不是为迭代而构建的吗?? It Only prints the array[0] not the array[1] .它只打印array[0]而不是array[1] Thanks.谢谢。

You'd be better off using nested foreach loops, not generally great coding practice but it'll do the job you're trying to do.你最好使用嵌套的 foreach 循环,这通常不是很好的编码实践,但它会完成你想要做的工作。

$json = json_encode($myInstance->getData($id));
$result = json_decode($json,true);

foreach ($result as $value) {
    foreach($value as $value_detail) {
        echo '<div>'.$value_detail['name'].'</div>';
    }
}

Your code will loop through all of the first level items in your JSON and display the first name from the first item, the second name from the second item, third from the third item, etc.您的代码将遍历 JSON 中的所有第一级项目,并显示第一个项目的第一个名称、第二个项目的第二个名称、第三个项目的第三个名称等。

The issue you are having might be because the $json array is 3D, eg您遇到的问题可能是因为$json数组是 3D 的,例如

[0 => 
  [ 
    ['name' => 'Foo'], ['name' => 'Bar'] 
  ] 
]

If that's the case then you might find that the foreach loop can be如果是这样,那么您可能会发现 foreach 循环可以是

foreach($result[0] as $value) {
    echo '<div>'.$value['name'].'</div>';
}

Try var_dump($result);尝试var_dump($result); to see what the data looks like.看看数据是什么样子的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM