按字母顺序分组首字母并传递id

时间:2013-08-14 13:15:56

标签: php sql foreach

与此解决的帖子有关:Group by first letter, alphabetically, best way?

如何将$ id从数据库传递到这个foreach循环中:

$res = array();

foreach($film as $f) {
    $currentletter = substr(html_entity_decode($f->title),0,1);
    $res[$currentletter][] = html_entity_decode($f->title);
}

foreach($res as $key=>$val){
   echo $key;
   foreach($val as $reqvals){
      echo $reqvals;
   }
}

2 个答案:

答案 0 :(得分:1)

如果我从评论中正确理解你,你可以将循环合并为一个;你不需要两个独立的循环。我假设你的数据库中的字段是'name'和'id';它假设您正在对数据库查询进行排序。

$currentletter = '';

while ($r = mysql_fetch_array($q)){
    $name = $r['name'];       // Read the variables from the row
    $id = $r['id'];

    $thisletter = substr($name,0,1);
    if ($currentletter != $thisletter) {  // only print out the letter if it's changed
        $currentletter = $thisletter;
        echo $currentletter;
    }

    echo $name;
    echo $id;
    echo "<br>";
}

答案 1 :(得分:0)

当你在foreach中使用$ val时,这意味着你的$val是一个数组。所以$ key对于$val数组来说是唯一的。你可以通过这种方式传递foreach中的$ key:

 $k = $key;
   foreach($val as $reqvals){
      echo "Supar Key: "$k." ".$reqvals;
      echo "<br>";
   }