【问题标题】:How to loop through this json decoded data in PHP?如何在 PHP 中遍历这个 json 解码数据?
【发布时间】:2013-08-27 11:44:13
【问题描述】:

我有这个需要解码的 JSON 产品列表:

"[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]"

我用json_decode() 在PHP 中对其进行解码后,我不知道输出是什么结构。我以为这将是一个数组,但在我要求count() 之后,它说它是“0”。如何遍历这些数据,以便获得列表中每个产品的属性。

谢谢!

【问题讨论】:

  • $decoded_json = json_decode($list);,然后将数组输出为 echo "
    "; print_r($decoded_json);回声“
    ”;并在此处粘贴输出

标签: php json


【解决方案1】:

要将 json 转换为数组,请使用

 json_decode($json, true);

【讨论】:

    【解决方案2】:

    您可以使用 json_decode() 它将您的 json 转换为数组。

    例如,

    $json_array = json_decode($your_json_data); // convert to object array
    $json_array = json_decode($your_json_data, true); // convert to array
    

    然后你可以像循环数组变量一样,

    foreach($json_array as $json){
       echo $json['key']; // you can access your key value like this if result is array
       echo $json->key; // you can access your key value like this if result is object
    }
    

    【讨论】:

      【解决方案3】:

      试试下面的代码:

      $json_string = '[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]';
      
      $array = json_decode($json_string);
      
      foreach ($array as $value)
      {
         echo $value->productId; // epIJp9
         echo $value->name; // Product A
      }
      

      获取计数

      echo count($array); // 2
      

      【讨论】:

        【解决方案4】:

        你看说明书了吗?

        http://www.php.net/manual/en/function.json-decode.php

        或者只是找到一些重复的?

        How to convert JSON string to array

        使用谷歌。

        json_decode($json, true);
        

        第二个参数。如果为真,则返回数组。

        【讨论】:

          【解决方案5】:

          你可以在 php fiddle 在线尝试代码,对我有用

           $list = '[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]';
          
          $decoded_list = json_decode($list); 
          
          echo count($decoded_list);
          print_r($decoded_list);
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2010-11-01
            • 1970-01-01
            • 1970-01-01
            • 2022-11-01
            • 2012-04-10
            • 1970-01-01
            相关资源
            最近更新 更多