我有按国家/地区划分城市列表的代码:
<?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”而不是值
答案 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)