I have a query which gets all records ordered by last_name. Now I would like to create a loop that groups these results by the first letter of the开发者_StackOverflow last name and display the letter above the group i.e.
A
-----------
Albert
Alfred
C
-----------
Charles
D
-----------
Delta etc...
Thanks!
Order the results by lastname
on MySQL
side and track the change of the first letter on PHP
side:
<?php
$rs = mysql_query("SELECT * FROM mytable ORDER BY lastname");
while ($rec = mysql_fetch_assoc($rs)) {
if ($initial !== strtoupper(substr($rec['lastname'], 0, 1)) {
$initial = strtoupper(substr($rec['lastname'], 0, 1));
print "$initial\n";
}
print $rec['lastname'] . "\n";
}
?>
$letter = null;
foreach ($array as $word) {
if ($letter != $word[0]) {
$letter = $word[0];
echo '<b>'.strtoupper($word[0]) . '</b><br/>';
}
echo strtoupper($word) . '<br/>';
}
and to tour query add line :
order by `your_field` asc
Allready tried something like this?
$last = '';
foreach($data as $key=>$row){
if(substr($row['last_name'],0,1)!=$last) echo '<br /><br />'.substr($row['last_name'],0,1).'<br />----------------<br />';
$last = substr($row['last_name'],0,1);
echo $row['last_name'];
}
In your view you could then loop the records and split them up:
$current = '';
foreach ($rows as $r) {
if (!$current || strtolower($r['name'][0]) != $current) {
$current = strtolower($r['name'][0]);
echo strtoupper($current).'<br />---------------';
}
echo $row['name'].'<br />';
}
in your query, try adding something like:
group by substr(last_name,1,1)
i.e.
select substr(last_name,1,1) as alpha, *
from tableName
group by substr(last_name,1,1)
Yes you can achive this using MySql
itself
In my case brand_name going to be list out as you expected.
Example :
SELECT id, upper(SUBSTR(brand_name, 1, 1)) AS alpha FROM products WHERE brand_name != '' group by alpha
UNION
SELECT id, upper(SUBSTR(brand_name, 1, 1)) AS alpha FROM products WHERE brand_name != '' order by brand_name COLLATE NOCASE
Result :
A
A Card
A Cef
A Cef O
B
Bacticef Tab
Bacticin
Bactidrox
Bactidrox Kid
........
Hope it will help someone.
精彩评论