php多维数组帮助需要

时间:2012-02-06 17:28:09

标签: php arrays

我有这个数组(缩短了这个问题),我需要提取country_code(此演示中的“AF”和“AL”),以便根据国家/地区将区域信息插入到表格中。

如何在迭代数组时获取国家/地区代码,这是正确的方法吗?

$countries = array("AF" => array("BDS" => "Badakhshan",
                                 "BDG" => "Badghis",
                                 "BGL" => "Baghlan",
                                 "BAL" => "Balkh",
                                 "BAM" => "Bamian",
                                 "DAY" => "Daykondi"),
                   "AL" => array("BR" => "Berat",
                                 "BU" => "Bulqizë",
                                 "DL" => "Delvinë",
                                 "DV" => "Devoll",
                                 "DI" => "Dibër",
                                 "DR" => "Durrës",
                                 "EL" => "Elbasan",
                                 "FR" => "Fier")
);

foreach ($countries as $country) {
  $country_code = $country[]; // How do I get the country code here?
  foreach ($country as $region_code => $region_name) {
    // insert region info into table
  } // foreach ($country as $region_code => $region_name)
} // foreach ($countries as $country)

4 个答案:

答案 0 :(得分:4)

foreach($countries as $code => $list) {
 foreach($list as $rcode => $name) {

 }
}

代码和rcode将具有两个区域代码

我在评论中提到,这是唯一的方法,但是,我会更正

foreach($countries as $country)
{
        $code = array_keys($countries, $country);
        $code = $code[0];
}

可能会得到你想要的东西,超级奇怪的方式来做这件事,我不建议使用它。第一种方法更好

答案 1 :(得分:2)

您的数组设置为key => value对,这意味着您有一个值和该值的标识符。

$myArray = array( "Key" => "Value" );

或者,就您的代码而言:

$myArray = array( "Country Code" => array( "Region" => "Codes" ) );

如果您希望在循环时获取密钥,请使用以下语法:

foreach ( $myArray as $key => $value ) {
  echo $key; // "Country Code"
  foreach ( $value as $region_key => $region_code ) {
    echo $region_key; // Region
  }
}

现在,您可以在每次迭代时访问标识符。

答案 2 :(得分:1)

好吧,你已经在嵌套循环中使用它了:

foreach ($countries as $country_code => $country) {
    foreach ($country as $region_code => $region_name) {
        // foobar
    }
}

变量$country_code则保存国家/地区代码。

答案 3 :(得分:0)

while($country = current($countries)){
    while($region = current($country)){
        echo "region:".$region."(".key($country).")"." country:".key($countries);
        next($country);
    }
    next($countries);
}