如何在PHP中访问嵌套的JSON

时间:2019-05-20 07:21:53

标签: php json

我正在尝试访问JSON对象中的“ note_id”。

php代码

<?php

$test = 
'{"username":"Ellaleeeeeee",
  "event_source":"browser",
  "event":
  "{
     \"notes\": [{\"note_id\": \"2771\"}]
  }"
}';

$jarray = json_decode($test, true);
$jevent = json_decode($jarray['event'], true);

var_dump($jevent);

?>

我尝试了$jevent['notes']['note_id'][0],但失败了。

请告诉我我该怎么做。谢谢!

1 个答案:

答案 0 :(得分:3)

您需要像下面这样更改代码:-

$jarray = json_decode($test, true);
$jevent = json_decode($jarray['event'], true);
echo $jevent['notes'][0]['note_id'];

输出:-{https://3v4l.org/0sOfm

如果您想获取所有note_id,然后使用foreach()

<?php

$test = 
'{"username":"Ellaleeeeeee",
  "event_source":"browser",
  "event":
  "{\"notes\": [{\"note_id\": \"2771\"},{\"note_id\": \"2772\"}]}"
}';

$jarray = json_decode($test, true);
$jevent = json_decode($jarray['event'], true);

foreach($jevent['notes'] as $jnotes){

    echo $jnotes['note_id'].PHP_EOL;
}

输出:-{https://3v4l.org/D7t0R