Jason
Jason

Reputation: 195

PHP: Nested json and value extraction

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!

Upvotes: 3

Views: 2511

Answers (3)

Krimson
Krimson

Reputation: 7664

Script:

$json = "......"                                          //Your json text. 
$decoded_array = json_decode($json)->{'issue'};           //Decode Json string
foreach($decoded_array as $issue){                        //Get all Issues
    foreach($issue->{'fields'}->{'people'} as $person){   //Get all people
        echo $person->{'emailAddress'}."<br/>";           //Get person's email
    }
}

OutPut:

[email protected]
[email protected]
[email protected]
[email protected]


live example:

http://codepad.org/R1K0Lysi

Upvotes: 0

Michael Berkowski
Michael Berkowski

Reputation: 270609

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;
  }
});

Upvotes: 2

StackSlave
StackSlave

Reputation: 10627

Try:

function people($peopleArray, $searchProperty, $forValueArray){
  $fva = array_map('strtolower', $forValuArray);
  foreach($peopleArray as $v){
    $sp = $v[$searchProperty]; $sl = strtolower($sp);
    if(in_array($sl, $fva)){
      $q[] = $sp;
    }
  }
  return isset($q) ? $q : 0;
}
if($ans = people($decoded_array, 'emailAddress', array('bob', 'john', 'jake', 'frank'))){
  print_r($ans);
}
else{
  echo 'no results found';
}

Upvotes: 0

Related Questions