I have this json below. I'm trying to get values using json_decode. I'm getting some of the values, but I'm having trouble with the deeply nested values. Here is the json:
{
"startAt": 0,
"issue": [
{
"id": "51526",
"fields": {
"people": [
{
"name": "bob",
"emailAddress": "[email protected]",
"displayName": "Bob Smith",
},
{
"name": "john",
"emailAddress": "[email protected]",
"displayName": "John Smith",
}
],
"skill": {
"name": "artist",
"id": "1"
}
}
},
{
"id": "2005",
"fields": {
"people": [
{
"name": "jake",
"emailAddress": "[email protected]",
"displayName": "Jake Smith",
},
{
"name": "frank",
"emailAddress": "[email protected]",
"displayName": "Frank Smith",
}
],
"skill": {
"name": "writer",
"id": "2"
}
}
}
]
}
I know I can get one value by doing this:
foreach ($decoded_array['issue'][0]['fields']['people'] as $person) {
echo $person['emailAddress'];
}
However, is there a simplistic way to get all the "emailAddresses" for bob,john,jake, and frank?
Thanks!
The easiest way really is just to loop, but nest loops first at $decoded_array['issue'] and then an inner loop over ['people']. Collect your addresses into an output array.
// Note: this assumes you called json_decode() with the second
// param TRUE to force an associative array..
// $decoded_array = json_decode($input_json, TRUE);
$addresses = array();
foreach ($decoded_array['issue'] as $i) {
foreach ($i['fields']['people'] as $person) {
// Append the address onto an output array
$addresses[] = $person['emailAddress'];
}
}
// De-dupe them if necessary
$addresses = array_unique($addresses);
print_r($addresses);
// Prints
Array
(
[0] => [email protected]
[1] => [email protected]
[2] => [email protected]
[3] => [email protected]
)
A slightly fancier method if you weren't certain of the structure except that the keys are named emailAddress would be to use array_walk_recurisve() to traverse the array looking for that key. This will collect all keys named emailAddress, not just those inside the ['people'] subarrays.
$addresses = array();
// Pass $addresses into the closure by reference so you can write to it
array_walk_recursive($decoded_array, function($value, $key) use (&$addresses) {
// Find *all keys* called emailAddress
if ($key == 'emailAddress') {
$addresses[] = $value;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With