划分foreach不能正常工作

时间:2014-01-24 18:15:12

标签: php arrays pdo foreach

我有按国家/地区划分城市列表的代码:

<?php
$pdo = new PDO(...);
$cities = $pdo->query('SELECT `city`, `country` FROM `cities` ORDER BY `id` ASC');
$cities->execute();
$data = array();
foreach($cities as $row) {
$data[$row['country']][] = $row['city'];
}
foreach($data as $country){
echo "<optgroup label='{$country}'>";
foreach($country as $city){
echo "<option value='{$city}'>{$city}</option>";
}
echo "</optgroup>";
}
?>

我在需要的地方获得了optgroups,但是使用了“Array”而不是值

1 个答案:

答案 0 :(得分:1)

那是因为$country是一个数组。你想要主数组元素的键。你可以用这个来实现:

foreach($data as $country => $cities){
echo "<optgroup label='{$country}'>";
  foreach($cities as $city){
  echo "<option value='{$city}'>{$city}</option>";
  }
echo "</optgroup>";
}

通过这种方式,您也可以获取密钥。你的数组是这样的:

$data = array(
  "Spain" => array(
    "Madrid",
    "Barcelona",
    "Valencia"),
  "UK" => array(
     "London",
     "Oxford"));

所以你试图在你的脚本中访问它(第一次迭代):

echo array(
    "Madrid",
    "Barcelona",
    "Valencia");

哪个不行(它会打印数组)。相反,您想要访问“西班牙”键,可以访问该键,如下所示:

 foreach ($smth as $Key => $Value)