I have the code for dividing the list of cities by country:
<?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>";
}
?>
I get optgroups where I need but with the word "Array" instead of the value
That's because $country
is an array. You want the key of that element of the main array. You can achieve that with this:
foreach($data as $country => $cities){
echo "<optgroup label='{$country}'>";
foreach($cities as $city){
echo "<option value='{$city}'>{$city}</option>";
}
echo "</optgroup>";
}
In this way you are also fetching the keys. Your array is like this:
$data = array(
"Spain" => array(
"Madrid",
"Barcelona",
"Valencia"),
"UK" => array(
"London",
"Oxford"));
So you were trying to access this in your script (for the first iteration):
echo array(
"Madrid",
"Barcelona",
"Valencia");
Which wouldn't work (it would print Array). Instead, you want to access the "Spain" key, which can be accessed writting the foreach like:
foreach ($smth as $Key => $Value)