Jump to content

Show first letter of a list once?


jarv

Recommended Posts

hi,

 

I have a list of towns and need to get the first letter from each town and just display it once before the start of that lettered group ie;

 

what I have:

 

Aberdeen

Arundel

Aberyswith

Bath

Bristol

Brighton

Cardiff

coventry

 

what I would like:

 

A

Aberdeen

Arundel

Aberyswith

B

Bath

Bristol

Brighton

C

Cardiff

coventry

 

here is the code which writes out my list:

 

<ul class="edgetoedge">
               <?php while($row1 = mysql_fetch_array($locals))
				{
				echo '<li class="forward"><a href="townpubs.php?RSTOWN='.$row1['RSTOWN'].'" rel="external">'.$row1['RSTOWN'].'<small class="listcounter">'.$row1['PubCount'].'</small></a></li>'; 
				}
				?>
            </ul>

Link to comment
https://forums.phpfreaks.com/topic/227371-show-first-letter-of-a-list-once/
Share on other sites

Two ways to get the first letter of a string:

$string = 'happy';

echo substr($string, 0, 1);

echo $string[0];

Both echo h.

 

algorithm for display:

 

$old_title = $title = '';

 

loop here till done

// do query

$title =$string[0];

if ($title == $old_title){

echo $string;

$old_title = $title;

}else{

echo $title; // <- make it bold

$old_title = $title;

} end loop

 

I see $row1['PubCount'] :D  Is this for information only or for a pub crawl? Or maybe a yankee invention the poker run?

It took me a little while to type this and you have a couple of answers already but I will post it anyway. I haven't tested it but it should get you going in the right direction.

<?php 

$alphabet = null;
while($row1 = mysql_fetch_array($locals)) {

if($alphabet != substs($row1['RSTOWN'],0,1)) {
	echo strtoupper(substr($row1['RSTOWN'],0,1)); // add your html formatting too.
	$alphabet = substr($row1['RSTOWN'],0,1);
}
echo '<li class="forward">
		<a href="townpubs.php?RSTOWN='.$row1['RSTOWN'].'" rel="external">'
		.$row1['RSTOWN'].
		'<small class="listcounter">'.$row1['PubCount'].'</small>
		</a>
	  </li>'; 
}

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.