twan
twan

Reputation: 2659

Sort array in alphabetical order and group them by first letter

How can I sort an array in alphabetical order and seperate into groups defined by the first letter?

I want to know how do do this with php.

I retrieve a list of names from the database.

What I am looking for:

enter image description here

My query:

//  Product names
$producten          = "SELECT * FROM `producten`";
$productencon       = $conn->query($producten);
$productencr        = array();
while ($productencr[] = $productencon->fetch_array());

Upvotes: 1

Views: 2189

Answers (3)

Alex - Exaland Concept
Alex - Exaland Concept

Reputation: 127

In PHP i use this function

$array = ["BABY", "BATEAU", "BEAUTY", "CARS","COURSE", "MANGER" ];



$startl=""; // current Starting letter
foreach($array as $o)
{
if (($c=substr($o, 0, 1)) != $startl) // if starting letter changed
{
    if ($startl) echo '</ul>';
    echo '<ul>'.$c.'</ul>'; // create new group
    $startl=$c;
}
echo '<li>' . $o . '</li>';
}

echo '</ul>'; // end the last group

Upvotes: 0

maddy
maddy

Reputation: 167

try this way ..

<?php 

$previous = null;
foreach($array as $value) {
    $firstLetter = substr($value, 0, 1);
    if($previous !== $firstLetter) echo "\n".$firstLetter."\n---\n\n";
    $previous = $firstLetter;

    echo $value."\n";
}

?>

Upvotes: 1

David
David

Reputation: 111

In SQL exists the feature of

OrderBy('coloumn_name','ASC')

so you can loop through this query

$query="
SELECT * 
FROM Table
WHERE 1
ORDERBY('coloumn_name','ASC')"
<?php 
foreach($query as $q)
{
//doSomeStuffHere
}
?>

Upvotes: 0

Related Questions