jarv Posted February 11, 2011 Share Posted February 11, 2011 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> Quote Link to comment https://forums.phpfreaks.com/topic/227371-show-first-letter-of-a-list-once/ Share on other sites More sharing options...
Roman Fedorov Posted February 11, 2011 Share Posted February 11, 2011 What you can make is execute the sql query ordered by alfabetical order. Then start writing towns keeping in memory the first letter, when you see that the first letter changes - write it Quote Link to comment https://forums.phpfreaks.com/topic/227371-show-first-letter-of-a-list-once/#findComment-1172767 Share on other sites More sharing options...
sunfighter Posted February 11, 2011 Share Posted February 11, 2011 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'] Is this for information only or for a pub crawl? Or maybe a yankee invention the poker run? Quote Link to comment https://forums.phpfreaks.com/topic/227371-show-first-letter-of-a-list-once/#findComment-1172780 Share on other sites More sharing options...
acefirefighter Posted February 11, 2011 Share Posted February 11, 2011 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>'; } Quote Link to comment https://forums.phpfreaks.com/topic/227371-show-first-letter-of-a-list-once/#findComment-1172782 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.