views:

111

answers:

2

I have an array containing arrays of names and other details, in alphabetical order. Each array includes the first letter associated with the name.

Array
(
    [0] => Array
        (
            [0] => a
            [1] => Alanis Morissette
        )

    [1] => Array
        (
            [0] => a
            [1] => Alesha Dixon
        )
    [2] => Array
        (
            [0] => a
            [1] => Alexandra Burke
        )

    [3] => Array
        (
            [0] => b
            [1] => Britney Spears
        )

    [4] => Array
        (
            [0] => b
            [1] => Bryan Adams
        )
)

I'd like to display them grouped by that first initial, eg:

A
-
Alanis Morissette
Alesha Dixon
Alexandra Burke

B
-
Britney Spears
Bryan Adams

etc...

Is this at all possible?

A: 

You can group them easily, even if they aren't sorted:

$groups=array();
foreach ($names as $name) {
    $groups[$name[0]][] = $name[1];
}

You don't even need to store the first initial to group them:

$names = array(
  'Alanis Morissette',
  'Alesha Dixon',
  'Alexandra Burke',
  'Britney Spears',
  'Bryan Adams',
  ...
);

$groups=array();
foreach ($names as $name) {
    $groups[$name[0]][] = $name;
}
outis
+2  A: 

Since your array is already sorted, you could just loop through and track the last letter shown. When it changes, you know you're on the next letter.

$lastChar = '';
foreach($singers as $s) {
    if ($s[0] != $lastChar) echo "\n".$s[0]."\n - \n";
    echo $s[1]."\n";
    $lastChar = $s[0];
} 
zombat
Thought I would add that you can get the first letter easily with substr(). Unless you have other reasons for your array structure, a regular array full of names would work easily for what you're doing. My opinion is if a multi-dimensional array is confusing you, then you probably need to rethink how you put it together.
Syntax Error
@Syntax Error: or you can use array brackets (http://php.net/manual/en/language.types.string.php#language.types.string.substr), as zombat and I do.
outis
Oops... don't know how I missed that. Derp.
Syntax Error
tawfekov