Reputation: 2659
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:
My query:
// Product names
$producten = "SELECT * FROM `producten`";
$productencon = $conn->query($producten);
$productencr = array();
while ($productencr[] = $productencon->fetch_array());
Upvotes: 1
Views: 2189
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
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
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