dongmi5177
2016-09-26 11:51
浏览 117

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

I have a JSON Object and I want to loop through the values:

$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.

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douzhi1972 2016-09-26 11:55
    已采纳

    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;
    }
    

    p.s not tested ;-)

    已采纳该答案
    打赏 评论
  • dtcn30461 2016-09-26 11:53

    The shortest way to iterate it and this way you don't care about index is to use foreach like this:

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

    For example you don't have a index 0 in your $obj. From what I see it starts from 1. This way it's working with any index (not just numeric)

    打赏 评论

相关推荐 更多相似问题