简体   繁体   English

如何在 PHP 中循环 JSON 对象值?

[英]How to loop through JSON object values in PHP?

I have a JSON Object and I want to loop through the values:我有一个 JSON 对象,我想遍历这些值:

$json = '{"1":a,"2":b,"3":c,"4":d,"5":e}';
$obj = json_decode($json, TRUE);
for($i=0; $i<count($obj['a']); $i++) {
    echo $i;
}

I want the $i to display the abcde that are the values in the object.我希望$i显示作为对象中值的abcde

Try using.尝试使用。

$json = '{"1":"a","2":"b","3":"c","4":"d","5":"e"}';
 $obj = json_decode($json, TRUE);

foreach($obj as $key => $value) 
{
echo 'Your key is: '.$key.' and the value of the key is:'.$value;
}

ps not tested ;-) ps未测试;-)

The shortest way to iterate it and this way you don't care about index is to use foreach like this:迭代它的最短方法和这种你不关心索引的方式是像这样使用foreach

foreach($obj as $value) {
 echo $value;
}

For example you don't have a index 0 in your $obj .例如,您的$obj没有索引 0。 From what I see it starts from 1. This way it's working with any index (not just numeric)从我所见,它从 1 开始。这样它就可以处理任何索引(不仅仅是数字)

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

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