访问JSON变量两个级别

时间:2017-04-22 10:36:23

标签: php json

这是一些示例JSON数据,它是EmojiOne项目提供的JSON数据的摘录。他们已经发布了3.0版本,但他们的JSON格式略有改变,之前我必须从JSON中提取数据的PHP代码不再有效。

single.json

{
  "1f469-2764-1f468": {
    "name": "couple with heart: woman, man",
    "category": "people",
    "order": 2426,
    "display": 0,
    "shortname": ":couple_with_heart_woman_man:",
    "code_points": {
      "base": "1f469-2764-1f468",
      "output": "1f469-200d-2764-fe0f-200d-1f468",
      "default_matches": [
        "1f469-200d-2764-fe0f-200d-1f468",
        "1f469-2764-fe0f-1f468"
      ],
      "greedy_matches": [
        "1f469-200d-2764-fe0f-200d-1f468",
        "1f469-2764-fe0f-1f468"
      ],
      "decimal": ""
    },
    "keywords": [
      "couple",
      "love",
      "man",
      "woman"
    ]
  }
}

这是我用来尝试从JSON中提取数据的一些PHP:

<?php
$str = file_get_contents('single.json');
$json_a = json_decode($str, true);

foreach($json_a as $key => $val) {

    $name = $val['name'];
    $shortname = $val['shortname'];
    $category = $val['category'];
    $emoji_order = $val['order'];
    $keywords = implode(',', $val['keywords']);

}
?>

如何从数据的base部分访问code_points的值?

1 个答案:

答案 0 :(得分:0)

$val应为multidimensional array,因此您可以通过以下方式访问base

$val['code_points']['base'];

Here是一个实例,它是一个简单的程序:

<?php
$str = <<<EOT
{
  "1f469-2764-1f468": {
    "name": "couple with heart: woman, man",
    "category": "people",
    "order": 2426,
    "display": 0,
    "shortname": ":couple_with_heart_woman_man:",
    "code_points": {
      "base": "1f469-2764-1f468",
      "output": "1f469-200d-2764-fe0f-200d-1f468",
      "default_matches": [
        "1f469-200d-2764-fe0f-200d-1f468",
        "1f469-2764-fe0f-1f468"
      ],
      "greedy_matches": [
        "1f469-200d-2764-fe0f-200d-1f468",
        "1f469-2764-fe0f-1f468"
      ],
      "decimal": ""
    },
    "keywords": [
      "couple",
      "love",
      "man",
      "woman"
    ]
  }
}
EOT;

$json_a = json_decode($str, true);

foreach($json_a as $key => $val) {

    $name = $val['name'];
    $shortname = $val['shortname'];
    $category = $val['category'];
    $emoji_order = $val['order'];
    $keywords = implode(',', $val['keywords']);
    $base = $val['code_points']['base'];

    echo 'Name: ', $name, "\n";
    echo 'Base: ', $base;

}
?>