获取 JSON 数据而不是将对象转换为数组,然后从数组中查找特定值


get json data thant convert object into array after that finding particular value from array

我想从链接中解析国家/地区名称,我使用以下两种方法来解析对象和数组来解决我的问题,但我得到的响应是空数组,请帮助我解决此代码中的问题。

   http://www.geognos.com/api/en/countries/info/all.json

<?php $result   = []; 
      $result = file_get_contents("http://www.geognos.com/api/en/countries/info/all.json"); 
      $result = json_decode($result); 
      function object_to_array($obj) {
         if(is_object($obj)) 
          $obj = (array) $obj;
    if(is_array($obj)) {
         $new = array();
    foreach($obj as $key => $val) {
        $new[$key] = object_to_array($val);
        }
    }
function recursive($needle, $array, $holder = array()) {
foreach ($array as $key => $val) {    
     if (gettype($val) == 'Array') {
        if ($key != $needle) {
            recursive($needle, $val);
        } elseif ($key == $needle) {
            if (!empty($val)) {
                array_push($holder, $val);
               }
            }
        }
    }
    return $holder;
}
        else $new = $obj;
        return $new;
}       

$new_result=array();
$another_result=array();
$new_result = object_to_array($result);
$another_result = recursive('Name',$new_result);
print_r($another_result); 

期待快速回复。

要获取所有国家/地区名称,您只需执行以下操作:

$jsonData = file_get_contents('http://www.geognos.com/api/en/countries/info/all.json');
$data = json_decode($jsonData, true);
$countries = array();
foreach($data['Results'] as $country) {
    $countries[] = $country['Name'];
}
echo $countries[0]; // will output "Bangladesh"

我希望我正确理解了你的问题。