drlnsli18864734 2013-11-04 06:36
浏览 26
已采纳

解码一个json数组对象

I am having a php function that returns a JSON object.

Running this code:

$obj = json_decode($result); print_r($obj); 

where $result is the output of the function. The $result is:

{"result":[{"name":"name1","title":"title1","type":"1","place":"place1"}, 
{"name":"name2","title":"title2","type":"1","place":"place2"}]}

My output is this:

stdClass Object ( [result] => Array ( [0] => stdClass Object ( [name] => name1 [title] => title1 [type] => 1 [place] => place1 ) 
[1] => stdClass Object ( [name] => name2 [title] => title2 [type] => 1 [place] => place2 ) ))   

So what I want is to access the name1,title1 and so on value for each of the items.

I tried this:

echo $obj->result[0];

for getting the first row, but it gives me nothing.

If I try something like this:

foreach ($obj as $key => $value) {
  var_dump ($value);
  foreach ($value as $feature => $item) {
     echo $feature.' =>' .$item;
  }
}

It enter the first loop only once (output is an array(2) and the items) and it does not enter the second for loop at all. I know that it has something to do with the arrays and the JSON objects but I cannot make it work.

Any help?

  • 写回答

3条回答 默认 最新

  • douxue4395 2013-11-04 06:52
    关注

    Try this instead:

    $json = json_decode($json);
    
    foreach($json->result as $index => $item) {
      // $item is an object now, you can access $item->name, $item->title, etc.
    }
    

    If you want to loop over each key inside that, you can do a foreach on $item with $key => $value;

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 对于知识的学以致用的解释
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败