在 foreach 循环中正确使用 foreach 循环

Correct use of foreach loop within foreach loop

我的数据库中有以下数据:

initial   |    word
---------------------------
   E      |    Example1
   E      |    Example2
   N      |    Nextexample1

期望的输出:

E
Example1
Example2

N
Nextexample1

因此对于每个首字母,它应该显示该首字母和所有以该首字母开头的单词。对我来说很重要:每个单词都应该显示在单独的 div 中,所以请不要提出 GROUP_CONCAT(wordSEPARATOR ', ') 的建议。

此时输出:

E
Example1

E
Example2

N
Nextexample1

我此时的代码:

<?php
    $pdo = new PDO('mysql:host=...');           
    $sql = "SELECT DISTINCT initial, word FROM `exampletable` ORDER by initial ASC";
    $stmt = $pdo->prepare($sql);
    $stmt->execute();

    if($stmtrecords = $stmt->fetchall(PDO::FETCH_ASSOC))
    {

    foreach($stmtrecords as $result)
    {
?>

<div>
    <?php echo $result['initial'];?>
</div>
<br>
<div>
    <?php echo $result['word'];?>
</div>
<br><br>

问题:

显然我需要一个额外的循环来解决这个问题,但我不知道该怎么做?

我会用group_concat作为

<?php
    $pdo = new PDO('mysql:host=...');           
    $sql = "SELECT initial, group_concat(word) as word FROM `exampletable` group by initial ORDER by initial ASC";
    $stmt = $pdo->prepare($sql);
    $stmt->execute();

    if($stmtrecords = $stmt->fetchall(PDO::FETCH_ASSOC))
    {

    foreach($stmtrecords as $result)
    {
       $words = $result['words'];
       $words_array = array();
       if(strlen($words) > 1) {
         $words_array = explode(',',$words);
       }
?>

<div>
    <?php echo $result['initial'];?>
</div>
<br>
<div>
    <?php
     if (count($words_array) > 0 ){
       foreach($words_array as $val){
         echo $val.'<br />';
       }
     }
    ?>
    <?php echo $result['word'];?>
</div>

您实际上不需要额外的循环,您只需要在循环中添加一些额外的逻辑。由于查询是按initial对数据进行排序的,所以只需要在循环中检查$result['initial']何时发生变化,此时只输出表头即可。

$initial = null;

foreach ($stmtrecords as $result) {
    if ($result['initial'] !== $initial) {
        $initial = $result['initial'];
        // output header div
    }
    // output word
}

请注意:在上面的代码中,您将数据库中的数据直接嵌入到 HTML 中。在插入 HTML 之前应该转义该数据。有关如何正确转义数据的详细信息,请参阅 phptherightway.com and the Zend Escaper