dorbmd1177 2017-01-11 21:29 采纳率: 100%
浏览 30
已采纳

PHP echo json具有键值

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?? It Only prints the array[0] not the array[1]. Thanks.

  • 写回答

1条回答 默认 最新

  • dongyan6910 2017-01-11 21:37
    关注

    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.

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

    The issue you are having might be because the $json array is 3D, e.g.

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

    If that's the case then you might find that the foreach loop can be

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

    Try var_dump($result); to see what the data looks like.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line