在PHP中访问JSON上的嵌套数组?

时间:2018-02-15 04:16:27

标签: php json nested

这是代码,它使用foreach访问部门和工作人员。

编辑:将更正几个粘贴错误

<?php

$json = '{
"boss": "Jeff",
"department": [{
    "office": "1111",
    "workers": "[{\"id_work\":\"123\",\"name\":\"mike\",\"mobile\":\"12345\"}]"
}]}';
$json_data = json_decode($json);
echo "Boss:".$json_data->boss;

echo "<br>";

foreach($json_data->deparment as $dep)
{

 echo "Office number:".$dep->office."<br>";

  foreach($dep->workers as $worker){
  echo "Worker ID: ".$worker->id_work."<br>";
  echo "Worker name : ".$worker->name."<br>";
  echo "Worker mobil: ".$worker->mobil."<br>";


}


}
?>

当我尝试执行foreach()时,我无法访问内部数组:

  

为foreach()提供的参数无效

如何访问嵌套数组的信息

1 个答案:

答案 0 :(得分:3)

$json内的json数据是错误的。解码没有出错,但你得到的数组不是你想要的,这就是为什么你在json_decode之后出错的原因。

您得到的错误是因为worker值是字符串格式。 你应该更新:

来自:"workers": "[{\"id_work\":\"123\",\"name\":\"mike\",\"mobile\":\"12345\"}]"

收件人:"workers": [{ "id_work": "123", "name": "mike", "mobile":"12345"}]

最终结果:

$json = '{
"boss": "Jeff",
"department": [{
    "office": "1111",
    "workers": [{ "id_work": "123", "name": "mike", "mobile":"12345"}]
}]}';

$json_data = json_decode($json);
echo "Boss:".$json_data->boss;
echo "<br>";

foreach($json_data->department as $dep)
{
    echo "Office number:".$dep->office."<br>";

    foreach($dep->workers as $worker){
        echo "Worker ID: ".$worker->id_work."<br>";
        echo "Worker name : ".$worker->name."<br>";
        echo "Worker mobil: ".$worker->mobile."<br>";
    }
}