Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.