/    Sign up×
Community /Pin to ProfileBookmark

Sectioning Data By 1st letter

Hi,

I’m retriving a bunch of products from a database, ordered alphabetically in my query. But when I echo out the list of products, I want to do this…

[code=php]
<?php

$result = mysql_query(“SELECT * FROM products ORDER BY prod_name ASC”) or die (mysql_error());
while ($row = mysql_fetch_array($result))
{
echo $row[‘prod_name’].'<br />’;
}
?>
[/code]

this outputs…

[QUOTE]

aprod1
aprod2
aprod3
bprod1
bprod2
bprod3….

[/QUOTE]

I would like this….

[QUOTE]

A
aprod1
aprod2
aprod3

B
bprod1
bprod2
bprod3….

[/QUOTE]

Hoping someone can advise me how!

Thanks in advance

Smithster

to post a comment
PHP

3 Comments(s)

Copy linkTweet thisAlerts:
@NoasITMar 29.2011 — [code=php]
$curletter = '';
while( $row=mysql_fetch_array($result) ) {
$firstletter = substr($row['prod_name'],0,1);
if( $firstletter != $curletter ) {
$curletter = $firstletter;
echo "<b>$curletter</b><br />";
}
echo $row['prod_name']."<br />";
}
[/code]


give that a shot.
Copy linkTweet thisAlerts:
@NogDogMar 29.2011 — I would probably dump it into a 2-D array, then use that to display it. (I'm not claiming it's a better way, just the way I like to do it. ? )
[code=php]
$result = mysql_query("SELECT * FROM products ORDER BY prod_name ASC") or die (mysql_error());
$data = array();
while ($row = mysql_fetch_array($result))
{
$data[substr($row['prod_name'], 0, 1)][] = $row;
}
foreach($data as $letter => $group)
{
echo "<h3>$letter</h3>n<ul>n";
foreach($group as $item)
{
echo "<li>".$item['prod_name']."</li>n";
}
echo "</ul>n";
}
[/code]
Copy linkTweet thisAlerts:
@smithsterauthorMar 29.2011 — Hi, thanks guys, I did manage to figure out how to do it in the end, and Nogdog it was very similar to your example.

Thanks

Smithster
×

Success!

Help @smithster spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...