在PHP中打印嵌套关联数组

时间:2018-01-30 00:00:41

标签: php arrays json

我正在使用此代码$json_output = (json_decode($json, true));从JSON转换为PHP中的关联数组。

生成的数组对我来说太难了,我需要只打印一些键和值,但它们是嵌套的,到目前为止我还没能做到,我打印的例子对于这个来说太基本了

这是我的JSON的一部分:

{
"project": {
    "company": "Company Name SA de CV",
    "name": "Project Name",
    "files": [
        {
            "project-id": "666666",
            "filenameOnDisk": "HH-ORG-CMD-GUI-File.docx",
            "uploaded-date": "2018-01-29T21:20:56Z",
            "private": "0",
            "version-id": "3939061",
            "status": "active",
            "tags": [
                {
                    "name": "OPD",
                    "id": "25047",
                    "color": "#9e6957"
                }
            ],
            "id": "3796128",
            "last-changed-on": "2018-01-29T21:21:46Z",
            "versions": [],
            "uploaded-by-user-first-name": "Someone",
            "uploaded-by-user-last-name": "Anything",
            "name": "HH-ORG-CMD-GUI-GUIA_RAPIDA_PARA_CREAR_PROCESOS",
            "size": "262747",
            "category-name": "Instructivos"
        },
        {
            "project-id": "666",
            etc...,
        },

解析时看起来像this

如何打印(假设)FilesOnDisk和Files数组的id键。

我不知道如何到达那个嵌套数组。

2 个答案:

答案 0 :(得分:0)

echo $json_output['project']['files'][0]['project-id'];
echo $json_output['project']['files'][0]['filenameOnDisk'];
echo $json_output['project']['files'][0]['version-id'];

或者你可以使用你想要的值数组将它放在foreach循环中(只要它们都在'files'数组中)。例如。

$wantedValues = array("project-id","filenameOnDisk","version-id"); 

foreach ($wantedValues as $value) { 
  echo $json_output['project']['files'][0][$value];
}

答案 1 :(得分:0)

我只需要在@SeeSamRun提供的代码中添加几行,以获得完整的"文件"阵列。

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css" integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ==" crossorigin="" />
<script src="https://unpkg.com/leaflet@1.3.1/dist/leaflet-src.js" integrity="sha512-IkGU/uDhB9u9F8k+2OsA6XXoowIhOuQL1NTgNZHY1nkURnqEGlDZq3GsfmdJdKFe1k1zOc6YU2K7qY+hF9AodA==" crossorigin=""></script>

<div id="map" style="height: 200px"></div>