jjj jjj - 18 days ago 5
JSON Question

PHP: Parsing JSON Tree

This will be extremely simple question, but please let me know how I can do this in PHP.

I have the following JSON structure that I need to parse:

{

"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"
}
]

}

}


To get the content of X node, I do this:

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


And that works nicely, producing:

CONTENT OF X


I can also fing all 'Subject' nodes of all 'EMAILS', by doing this:

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


So I get:

heading a1
heading b1
heading c1


However, I don't know how to iterate over EMAIL array, so it produces the following list of headers only:

EMAIL A
EMAIL B
EMAIL C


And it would very much help to know how to combine it together, so I get following output:

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

Answer

If you only want the first occurance like your question suggests then you can do

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

RESULT:

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

Otherwise if you want all the occurances of the inner array you can do

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

RESULT:

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
Comments