使用以下格式从 PHP 中的 JSON 数组获取值?

Get values from JSON array in PHP with the following format?

我从与我合作的 Android 开发人员那里得到了这个数组,我必须从以下数组中获取键 name 的值:

[ 
   { 
      "data":"[{\"name\":\"step 1 kdfhghdkgjdf\nkjdhfgkjhdkjghd\nkdfjhgkjdhfg\n\n\ndfjhgkjdfjhgdfgd\n\"},{\"name\":\"step 2 dhfgkjdfhkhkjchjkfd\ndkjhjdf\njhkdfhkghdkfhgkdhg\n\n\ndfjhgkjdfhgdfhgkjdhfgkjhdf\"},{\"name\":\"step 3 kkkkkkkkkk\"},{\"name\":\"step 4 ljlejrhlflhgf\n\n\ndfhjk\"}]",
      "status":1
   }
]

我已尝试执行以下操作:

 <?php
    $s = '[
  {
    "data": "[{\"name\":\"step 1 kdfhghdkgjdf\nkjdhfgkjhdkjghd\nkdfjhgkjdhfg\n\n\ndfjhgkjdfjhgdfgd\n\"},{\"name\":\"step 2 dhfgkjdfhkhkjchjkfd\ndkjhjdf\njhkdfhkghdkfhgkdhg\n\n\ndfjhgkjdfhgdfhgkjdhfgkjhdf\"},{\"name\":\"step 3 kkkkkkkkkk\"},{\"name\":\"step 4 ljlejrhlflhgf\n\n\ndfhjk\"}]",
    "status": 1
  }
]';
    $obj = json_decode($s,true);
    echo $obj[0]['data']
    ?> 

这给了我以下输出:

[
  {
    "name": "step 1 kdfhghdkgjdf kjdhfgkjhdkjghd kdfjhgkjdhfg dfjhgkjdfjhgdfgd "
  },
  {
    "name": "step 2 dhfgkjdfhkhkjchjkfd dkjhjdf jhkdfhkghdkfhgkdhg dfjhgkjdfhgdfhgkjdhfgkjhdf"
  },
  {
    "name": "step 3 kkkkkkkkkk"
  },
  {
    "name": "step 4 ljlejrhlflhgf dfhjk"
  }
]

但我只想要键 name 的值,例如:

step 1 kdfhghdkgjdf kjdhfgkjhdkjghd kdfjhgkjdhfg dfjhgkjdfjhgdfgd
step 2 dhfgkjdfhkhkjchjkfd dkjhjdf jhkdfhkghdkfhgkdhg dfjhgkjdfhgdfhgkjdhfgkjhdf
step 3 kkkkkkkkkk
.
.
.

我的问题与这个类似: Get value from JSON array in PHP 除了格式不同。

我可以得到这种格式的值吗?如果是这样,如何?如果不是,是不是格式不对?

首先,"data" 字段中没有 json 结构,只有一个包含 json 数据的字符串。

所以你做错了,在将数据转换成常数值的时候。您必须先将所有反斜杠加倍。

然后就可以得到"data"元素,再执行一次json_decode

<?php
    $s = '[
  {
    "data": "[{\"name\":\"step 1 kdfhghdkgjdf\\nkjdhfgkjhdkjghd\\nkdfjhgkjdhfg\\n\\n\\ndfjhgkjdfjhgdfgd\\n\"},{\"name\":\"step 2 dhfgkjdfhkhkjchjkfd\\ndkjhjdf\\njhkdfhkghdkfhgkdhg\\n\\n\\ndfjhgkjdfhgdfhgkjdhfgkjhdf\"},{\"name\":\"step 3 kkkkkkkkkk\"},{\"name\":\"step 4 ljlejrhlflhgf\\n\\n\\ndfhjk\"}]",
    "status": 1
  }
]';
    $obj = json_decode($s,true);
    $data = json_decode($obj[0]['data'], true);

    foreach($data as $item) {
      print($item['name'] . "\r\n");
    }

假设 $obj[0]['data'] 实际上有您发布的 JSON,只需解码并提取 name 列:

foreach(array_column(json_decode($obj[0]['data'], true), 'name') as $name) {
    echo $name;
}