NickC217
NickC217

Reputation: 326

Accessing JSON object with PHP, Random Object Name

I am trying to parse out certain things within the JSON code, but the problem is that the two groups of arrays that have the information in it I need have random names, here is from the var_dump:

array (size=2)
'results' => 
array (size=1)
  0 => string 'Phone.5d5b6fef-a2e0-4b08-cfe3-bc7128b776c3.Durable' (length=50)
'dictionary' => 
array (size=3)
  'Person.51f28c76-2993-42d3-8d65-4ea0a66c5e16.Ephemeral' => 
    array (size=8)
      'id' => 
        array (size=5)
          ...
      'type' => null
      'names' => 
        array (size=1)
          ...
      'age_range' => null
      'locations' => null
      'phones' => 
        array (size=1)
          ...
      'best_name' => string 'John Smith' (length=15)
      'best_location' => null
  'Location.28dc9041-a0ee-4613-a3b0-65839aa461da.Durable' => 
    array (size=30)
      'id' => 
        array (size=5)
          ...
      'type' => string 'ZipPlus4' (length=8)
      'valid_for' => null
      'legal_entities_at' => null
      'city' => string 'City' (length=8)
      'postal_code' => string '12345' (length=5)
      'zip4' => string '4812' (length=4)
      'state_code' => string 'MO' (length=2)
      'country_code' => string 'US' (length=2)
      'address' => string 'Main St, City, MO 12345-4812' (length=33)
      'house' => null

No I am trying to get best_name from under the part that starts with Person and address under Location. But when I do:

$string = file_get_contents($url);
$json=json_decode($string,true);
var_dump($json);
echo $json['dictionary']['Person']['best_name'];

I get Undefined index: Person error, because the actual object name for Person is: Person.51f28c76-2993-42d3-8d65-4ea0a66c5e16.Ephemeral which is different every time I do a search. Is there a way to do this without putting the random generated line in?

Hopefully this makes sense, thanks for the help in advance!

Upvotes: 0

Views: 667

Answers (2)

Will
Will

Reputation: 2333

How about something like this ... loop through $json['dictionary']'s index keys to find something that starts with "Person".

$foundIt = false;
foreach (array_keys($json['dictionary']) as $key) {
    if (substr($key,0,6) == 'Person') {
         $foundIt = $key;
         break;
    }
}
if ($foundIt) { echo $json['dictionary'][$foundIt]['best_name']; }

Upvotes: 1

sasy0174
sasy0174

Reputation: 26

If the Person key always starts with the string "Person", than simply do a foreach and check the key which contains this string.

Like:

foreach ($json['dictionary'] as $key => $value) {
  if (preg_match('/^Person/', $key)) {
    echo $json['dictionary'][$key]['best_name'];
  }
}

Of course this get complicated, if you have multiple keys which start with "Person".

You can do the same with "Location" or any other string you need.

Upvotes: 1

Related Questions