【问题标题】:get json data thant convert object into array after that finding particular value from array在从数组中找到特定值之后,获取 json 数据,然后将对象转换为数组
【发布时间】:2015-02-19 03:22:35
【问题描述】:

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

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

期待快速回复。

【问题讨论】:

    标签: php arrays json recursion


    【解决方案1】:

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

    $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"
    

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

    【讨论】:

      猜你喜欢
      • 2020-03-29
      • 1970-01-01
      • 2021-06-12
      • 1970-01-01
      • 1970-01-01
      • 2018-08-22
      • 1970-01-01
      • 2016-06-06
      • 1970-01-01
      相关资源
      最近更新 更多