Reputation: 4695
Here is my code:
<div class="widgeter-content no-padding">
<ul id="contacts">
<?php
while ($r = mysql_fetch_array($q)){
$currentletter = substr($name,0,1);
if ($currentletter != $lastletter){
?>
<!-- start li data group for specific alphabetic letter -->
<li data-group="<?=$currentletter;?>">
<a class="title"><?=strtoupper($currentletter);?></a>
<?
}
?>
<ul>
<li>
<a href="#">
<span><?=$name;?></span>
</a>
</li>
</ul>
<?
if ($currentletter != $lastletter){
?>
</li>
<!-- end data group (not currently working, ends on first result) -->
<?
}
$lastletter = $currentletter;
}
?>
</ul>
</div>
What I am trying to do:
A:
Alfred
Annie
B:
Bob
Billy
As you can see, the data is wrapped in an li data group.
The first part of the code works perfectly, but the last part (where I'm trying to put the closing li tag before the end comment, shows after the first result of each loop, where it needs to show at the END of each letters results).
What would be the best way to do this? I'm sure its quite obvious what I'm trying to achieve but I can't think of a logical way to get the code structuring how I want it to.
Thank you
Upvotes: 2
Views: 3280
Reputation: 32730
$res = array();
while ($r = mysql_fetch_array($q)){
$currentletter = substr($name,0,1);
$res[$currentletter][] = $name;
}
foreach($res as $key=>$val){
/// here you add your li
/// here $key will give you letter and $val will give you name
echo $key;
foreach($val as $reqvals){
echo $reqvals;
echo "<br>";
}
}
Upvotes: 1
Reputation: 45124
What would be the best way to do this?
If you are fetching row from the database why can not rather GROUP BY there and get the records. That's the preferred way of doing it.
Assuming that the column name is first_name
group by substr(first_name,1,1)
Upvotes: 0