PHP:解析JSON树

时间:2016-11-17 11:19:47

标签: php json

这将是一个非常简单的问题,但请告诉我如何在PHP中执行此操作。

我有以下需要解析的JSON结构:

{

    "X": "CONTENT OF X",
    "Y": "CONTENT OF Y",
    "Z": "CONTENT OF Z",

    "EMAILS": {

        "EMAIL A": [{
                "Subject": "heading a1",
                "Body": "text"
            }, {
                "Subject": "heading a2",
                "Body": "text"
            }
        ],
        "EMAIL B": [{
                "Subject": "heading b1",
                "Body": "text"
            }, {
                "Subject": "heading b2",
                "Body": "text"
            }
        ],
        "EMAIL C": [{
                "Subject": "heading c1",
                "Body": "text"
            }, {
                "Subject": "heading c2",
                "Body": "text"
            }
        ]

    }

}

要获取X节点的内容,我这样做:

$string = file_get_contents($url);
$json = json_decode($string, true);
echo $json['X'];

这很好用,产生:

CONTENT OF X

通过这样做,我还可以查看所有“EMAILS”的所有“主题”节点:

foreach ($json['EMAILS'] as $value) {
 echo $value[0]['Subject']
}

所以我得到了:

heading a1
heading b1
heading c1

但是,我不知道如何迭代EMAIL数组,所以它只生成以下标题列表:

EMAIL A
EMAIL B
EMAIL C

知道如何将它们组合在一起会非常有帮助,所以我得到以下输出:

EMAILS - EMAIL A - Subject - heading a1
EMAILS - EMAIL B - Subject - heading b1
EMAILS - EMAIL C - Subject - heading c1

1 个答案:

答案 0 :(得分:2)

如果您只希望第一次出现问题,那么您可以做

foreach ($json['EMAILS'] as $name => $emails) {
    echo sprintf("EMAILS - %s %s\n", $name, $emails[0]['Subject']);
}

结果:

EMAILS - EMAIL A heading a1
EMAILS - EMAIL B heading b1
EMAILS - EMAIL C heading c1

否则,如果你想要内部数组的所有出现,你可以做

foreach ($json['EMAILS'] as $name => $emails) {
    foreach ($emails as $email) {
        echo sprintf("EMAILS - %s %s\n", $name, $email['Subject']);
    }
}

结果:

EMAILS - EMAIL A heading a1
EMAILS - EMAIL A heading a2
EMAILS - EMAIL B heading b1
EMAILS - EMAIL B heading b2
EMAILS - EMAIL C heading c1
EMAILS - EMAIL C heading c2