访问PHP json_encode中的嵌套值

时间:2016-03-11 18:18:30

标签: php arrays json multidimensional-array

我将数组转换为JSON,如何从中获取slug的值?

{
  "230": {
    "term_id": 230,
    "name": "Executive Committee",
    "slug": "executive_committee",
    "term_group": 0,
    "term_taxonomy_id": 241,
    "taxonomy": "team_member_filter",
    "description": "",
    "parent": 0,
    "count": 1,
    "object_id": 1561,
    "filter": "raw"
  }
}

当然,每个实例的第一个值“230”是不同的。如何访问循环内每个实例的“slug”值?

我最初在$variable中有这个数组:

  Array ( 
   [230] => stdClass Object ( 
      [term_id] => 230
      [name] => Executive Committee 
      [slug] => executive_committee
      [term_group] => 0 
      [term_taxonomy_id] => 241 
      [taxonomy] => team_member_filter
      [description] =>
      [parent] => 0 
      [count] => 1 
      [object_id] => 1561 
      [filter] => raw 
   )   
)

为什么$variable['slug']不会返回任何内容?

1 个答案:

答案 0 :(得分:3)

使用json_decode()然后您可以像数组一样访问:

$items = json_decode($variable, true); // 'true' here makes the json an associative array
foreach($items AS $item) {
    echo $item['slug']; // because it is associative  you can access each value by name
}

这是您在上面提供的JSON的回声executive_committee

从原始数组($variable)开始,你会做同样的事情:

foreach($variable AS $item) {
    echo $item->slug; // because you have an object, not an array 
}