riefart
riefart

Reputation: 21

group by first letter alphabetically

With the following script, values ​​are entered alphabetically sorted under the capital letter. However, I can't get $author into the while statement so it appears with 'title'.

I want the last html part included in the while statement. But no matter what I try, it doesn't work What am I doing wrong?

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

Upvotes: 0

Views: 99

Answers (2)

Martin
Martin

Reputation: 22760

As an aside to DinoCoderSaurus' answer, you have

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

What you probably want is:

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

or

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

Yes, you need to instruct PHP to print the variable to the screen.

See also:

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

Upvotes: 0

DinoCoderSaurus
DinoCoderSaurus

Reputation: 6520

When the while loop is finished executing, there are no $links or $authors; they have not been saved anywhere.

One option would be to save them in the $res array. Perhaps something like:

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

The "last html part" could be created in the foreach($val as $reqvals) (remembering of course that $reqvals is a list) because it would have access to the "whole row".

Upvotes: 1

Related Questions