Separate results by blocks

0

I have a query:

SELECT * FROM items ORDER BY title ASC

which brings me the results ordered in alphabetical order.

now, separate with php, each block the results according to your initial letter

Letter A

Alibaba
Andres

Letter B

Banana
Bruno

and so on.

Code as printed

while ($row = $query -> result()) {
echo $row['title'].'<br />';
}
    
asked by Jadel 05.07.2017 в 23:37
source

1 answer

0

This code can help you.

The logic is as follows: we assume that the array is already ordered, so we focus on extracting the first character of each element of the array, when we have it, we store it and review it in each iteration, when we see a change we make a new div.

$tmp = "";
$band = false;
while ($row = $query -> result()) {
    // esta condicipon solo es para la primera iteración
    if (!$band):
        $tmp = substr($row['title'], 0, 1);;
        echo "<div style='border: 1px dotted gray; margin: 3px;'>";
        echo "<h1>Letra ".$tmp."</a>";
        echo "<p>";
        $band = true;
    endif;
    // extraer la primera letra de title
    $init = substr($row['title'], 0, 1);
    if ($tmp === $init):
        echo "<h3>".$row['title']."</h3>";
    else:
        $tmp = $init;
        echo "</p></div>";
        echo "<div style='border: 1px dotted gray; margin: 3px;'>";
        echo "<h1>Letra ".$init."</h1><p>";
        echo "<h3>".$row['title']."</h3>";
    endif;
}
echo "</p></div>";
    
answered by 06.07.2017 / 00:21
source