PHP - 来自json的打印对象键

时间:2013-10-12 07:40:10

标签: php arrays json object

抱歉,我知道了一个愚蠢的问题,但我遇到了麻烦,我无法从这个阵列打印国家:

$array =   json_decode('[
   {
       "Afghanistan": {
           "lang": "en",
           "browser_code": []
       }
   },
   {
       "Albania": {
           "lang": "en",
           "browser_code": []
       }
   },
   {
       "Algeria": {
           "lang": "en",
           "browser_code": []
       }
   }
]');

我的尝试:

foreach($array as $key){
 foreach($key as $k){
  echo $k;
}
}

我在很多方面尝试使用foreach(){}循环,但我遇到逻辑问题,我只需要打印出来:

Afghanistan, Algeria, Algeria

有任何线索吗?

2 个答案:

答案 0 :(得分:10)

$arrJson = json_decode('[
   {
       "Afghanistan": {
           "lang": "en",
           "browser_code": []
       }
   },
   {
       "Albania": {
           "lang": "en",
           "browser_code": []
       }
   },
   {
       "Algeria": {
           "lang": "en",
           "browser_code": []
       }
   }
]');
foreach($arrJson as $key=>$val){
  foreach($val as $k=>$v){
    echo $k." , ";
  }
}

Live demo

答案 1 :(得分:0)

试试这个:

foreach($array as $item) {
    foreach ($item as $countryName => $countryData) {
        echo $countryName; // Should be "Afghanistan"
        echo $countryData; // Should be array('lang' => 'en', 'browser_code' => array())
    }
}