douyueqing1530 2014-01-24 18:15
浏览 47
已采纳

划分foreach不能正常工作

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

  • 写回答

1条回答 默认 最新

  • drcvvkx914772 2014-01-24 18:18
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗