使用PHP访问JSON对象,随机对象名称


Accessing JSON object with PHP, Random Object Name

我试图解析JSON代码中的某些内容,但问题是其中包含我需要的信息的两组数组具有随机名称,这是来自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

不,我试图从以Person开头的部分下获取best_name,并在Location下获取address。但当我这样做时:

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

我得到Undefined index: Person错误,因为Person的实际对象名称是:Person.51f28c76-2993-42d3-8d65-4ea0a66c5e16.Ephemeral,每次搜索都不一样。有没有一种方法可以在不放入随机生成的行的情况下做到这一点?

希望这是有意义的,感谢您的提前帮助!

如果Person键总是以字符串"Person"开头,那么只需执行foreach并检查包含此字符串的键即可。

类似:

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

当然,如果你有多个以"Person"开头的键,这会变得很复杂。

您可以对"Location"或任何其他需要的字符串执行同样的操作。

这样的东西怎么样。。。循环使用$json['dictionary']的索引键来查找以"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']; }