List alphabetically ordered Mysql records in PHP

Asked

Viewed 62 times

-2

I created a table to store records of names of people where the field a_tipo store the alphabet letter related to the name, the table structure is like this:

inserir a descrição da imagem aqui

With PHP I made the connection to the database and display the list of records:

$sql = "SELECT * FROM `a_cadastro` ORDER BY `a_tipo` ASC;";

I ordered it by alphabet, which was stored in the field a_tipo ascending mode, and the listing is ok.

The difficulty I’m facing is that, with each list of names starting with the letter A, I need to create a glossary, which would be displayed like this:

inserir a descrição da imagem aqui

I’m not able to organize the logic to list in this way, which in HTML would be:

<h1>Lista de nomes</h1>

<h2>A</h2>

<ul>
  <li>Abilio</li>
  <li>Acácio</li>
  <li>Ademilson</li>
  <li>Afonso</li>
</ul>

<h2>B</h2>

<ul>
  <li>Benedita</li>
  <li>Bernardo</li>
  <li>Bianca</li>
  <li>Beatriz</li>
</ul>

[.... All letters, if there are names in the records ....]

Someone can help, it’s not ill will, but I don’t know where to start.

1 answer

3


It follows a quick script that I did, I could not test, but I believe it works. No foreach you scroll through the database data you can switch to while if you are implementing in such a way.

<?php
echo '<h1>Lista de nomes</h1>';
$utimaLetra = '';
foreach($dados as $dado) {

    if(strtoupper($utimaLetra) != strtoupper(substr($dado['a_tipo'], 0, 1))) {
         if($utimaLetra != '') {
             echo '</ul>';
         }
         echo '<h2>'.strtoupper(substr($dado['a_tipo'], 0, 1)).'</h2>';
         echo '<ul>';
         $utimaLetra = strtoupper(substr($dado['a_tipo'], 0, 1));
    }

    echo '<li>'.$dado['a_tipo'].'</li>';
}

echo '</ul>';
  • I understood the logic and applied, thank you for your time!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.