首页 > 解决方案 > 按字母顺序按首字母分组

问题描述

使用以下脚本,在大写字母下按字母顺序输入值。但是,我无法$author进入 while 语句,因此它显示为“标题”。

我希望将最后一个 html 部分包含在 while 语句中。但无论我尝试什么,它都不起作用我做错了什么?

<?php
if ($stmt = $mysqli->prepare("select `link`, `titel`, `author` from `books` where `id`=? order by `titel`asc ")) {
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $stmt->bind_result($link, $titel, $author);
    while ($stmt->fetch()) {
        $titel = mb_strimwidth("$titel", 0, 30, "...");
        $letter = substr($titel, 0, 1);
        $res[$letter][] = $titel;

    }
    foreach ($res as $key => $val) {
        ?>
        <div class="<?php $letter; ?>"></div>
        <?php

        echo $key; //shows capital letter
        foreach ($val as $reqvals) {
            echo $reqvals; //shows 'titel'
            echo "<br>";
        }
    }
    ?>

    <a href="#se_annonce<?php echo $link; ?>" class="popup-with-zoom-anim">
        <div class="box">
            <div class="author">By <?php $author; ?></div>
        </div>
    </a>
    <?php

    $stmt->close();
}
?>  

标签: phpmysqli

解决方案


当while循环执行完毕,没有$links或$authors;他们没有被保存在任何地方。

一种选择是将它们保存在$res数组中。也许是这样的:

$res[$letter][] = [$titel, $author, $link];

可以在foreach($val as $reqvals)(当然记住那$reqvals是一个列表)中创建“最后一个 html 部分”,因为它可以访问“整行”。


推荐阅读