Jump to content

organize data alphabetically


We Must Design

Recommended Posts

Hi, I am taking data from a database and I was wondering if there is any way I can organize the data into alphabetical sections like my example below:

 

A

_____________________________________

Adam

Alan

 

B

_____________________________________

Barbara

Benice

 

I know how to organize the data alphabetically but I dont have a clue how I would seperate for each letter of the alphabet.

 

Thanks,

 

Chris

Link to comment
https://forums.phpfreaks.com/topic/70007-organize-data-alphabetically/
Share on other sites

I think you'd want to check the first letter of each name inside the loop, and if it's different to the first letter of the previous name, then echo that letter. Something like:

 

<?php
$names = array('Tom','Dick','Harry','Jim','Bob','Adam','Alan','Barbara','Benice');
sort($names);
$curr_letter = '';
foreach($names as $v){
	if($v[0] != $curr_letter){
		$curr_letter = $v[0];
		echo '<br />'.$v[0].'<br /><hr />';
}
echo $v.'<br />';

}
?>

 

I just used an array to test, so you'll have to change that a bit to work with your database query.

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.