【问题标题】:How to iterate array correctly? [duplicate]如何正确迭代数组? [复制]
【发布时间】:2017-08-16 21:24:36
【问题描述】:

我有一个$content 变量,echo $content 显示以下内容:

{
   "ID": 181271,
   "version_id": 2137,
   "theme_id": 2,
   "score": null,
   "showstopper": 0
}

显然echo $content['ID'] 应该显示181271

所以我需要迭代所有字段。我在做:

 foreach ($content as $key => $value) 
 {
      echo $key ;
      echo $value;
 }

它给了我一些疯狂的结果!

incrementing 1 exists 1 wasRecentlyCreated timestamps 1

预期结果:

ID 181271
version_id 2137
etc...

【问题讨论】:

    标签: php arrays json string iterator


    【解决方案1】:

    Hope this will work, PHP code demo

    使用 $array = json_decode($content, true); 将 json 字符串转换为数组

    $content = '{"ID":181271,"version_id":2137,"theme_id":2, "score":null,"showstopper":0}';
    $array = json_decode($content, true);
    foreach ($array as $key => $value)
    {
        echo $key;
        echo $value;
    }
    

    【讨论】:

      【解决方案2】:

      因为它是一个 json 字符串,而不是一个数组。您必须将 json_decode 放入一个数组中。然后就可以访问了。

      【讨论】:

        猜你喜欢
        • 2022-10-07
        • 1970-01-01
        • 2022-06-12
        • 2011-08-24
        • 1970-01-01
        • 1970-01-01
        • 2021-09-07
        • 1970-01-01
        • 2019-11-02
        相关资源
        最近更新 更多