按字母顺序按首字母分组

时间:2020-02-29 12:05:05

标签: php mysqli

使用以下脚本,在大写字母下方按字母顺序输入值。 但是,我无法将$author放入while语句中,因此它显示为'title'。

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

<?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();
}
?>  

2 个答案:

答案 0 :(得分:1)

while循环完成执行后,没有$link$author s;他们尚未保存在任何地方。

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

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

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

答案 1 :(得分:0)

除了DinoCoderSaurus'答案之外,您还有

 <div class="author">By <?php $author; ?></div> 

您可能想要的是:

<div class="author">By <?php print $author; ?></div>

<div class="author">By <?=$author;?></div>

是的,您需要指示PHP将变量打印到屏幕上。

另请参阅:

  <div class="<?php print $letter; ?>"></div>