PHP:从JSON String获取值?

时间:2017-09-25 12:24:13

标签: php json

我有一个看起来像这样的字符串:

[
   {
      "id":"2",
      "price":"39.99",
      "timeStamp":"1506264307167",
      "quantity":"1",
      "colours":"Green",
      "pid":"234234234"
   },
   {
      "id":"2",
      "price":"39.99",
      "timeStamp":"1506264311757",
      "quantity":"1",
      "colours":"Blue",
      "pid":"234234234"
   }
]

我需要使用PHP从JSON string获取id。

所以我尝试了这个:

$details = '[
       {
          "id":"2",
          "price":"39.99",
          "timeStamp":"1506264307167",
          "quantity":"1",
          "colours":"Green",
          "pid":"234234234"
       },
       {
          "id":"2",
          "price":"39.99",
          "timeStamp":"1506264311757",
          "quantity":"1",
          "colours":"Blue",
          "pid":"234234234"
       }
    ]';

$details = json_encode($details, true);

$array = json_decode($details, true);
$oid = $array['id'];


echo $oid;

上面的代码是在while循环中,因此echo $oid应该回显id 多次。

无论如何,上面的代码只打印这个:

[
[

当我查看错误日志时,我看到了这个错误:

PHP Warning:  Illegal string offset 'id'

有人可以就此问题提出建议吗?

提前致谢。

2 个答案:

答案 0 :(得分:2)

<?php
$details = '[
       {
          "id":"2",
          "price":"39.99",
          "timeStamp":"1506264307167",
          "quantity":"1",
          "colours":"Green",
          "pid":"234234234"
       },
       {
          "id":"2",
          "price":"39.99",
          "timeStamp":"1506264311757",
          "quantity":"1",
          "colours":"Blue",
          "pid":"234234234"
       }
    ]';


$array = json_decode($details, true);

for($i=0;$i<count($array);$i++){
    $idValue = $array[$i]['id'];
    echo $idValue;
}

您需要一个循环来遍历所有嵌套数组并获取所有ID。

答案 1 :(得分:0)

请尝试以下代码:

<?php
$details = '[
       {
          "id":"2",
          "price":"39.99",
          "timeStamp":"1506264307167",
          "quantity":"1",
          "colours":"Green",
          "pid":"234234234"
       },
       {
          "id":"2",
          "price":"39.99",
          "timeStamp":"1506264311757",
          "quantity":"1",
          "colours":"Blue",
          "pid":"234234234"
       }
    ]';


$array = json_decode($details, true);
$oid = $array[0]['id'];


echo $oid;

而不是将json字符串编码为json。直接将其解码为PHP数组。并使用[0]索引获取第一个Json Object