-6

I have an array of users like this one:

Array
(
    [9] => Array
        (
            [id] => 246
            [name] => John
            [surname] => Doe 
        )
   [13] => Array
        (
            [id] => 246
            [name] => Mark
            [surname] => Doe 
        )

    [19] => Array
        (
            [id] => 246
            [name] => Bill
            [surname] => Buffalo 
        )
)

Id like to have an output like this:

<h4>B</h4>
 Buffalo Bill
<h4>D</h4>
 John Doe
 Mark Doe

How can I accomplish this result?

Pennywise83
  • 1,784
  • 5
  • 31
  • 44
  • 1
    read up on the `usort()` function, and all the similar questions listed on the right hand side of this page. – SDC Dec 06 '12 at 14:32
  • I don't need to order the array, but only to group each surnames under the first letter of the surname. – Pennywise83 Dec 06 '12 at 14:35
  • Possible Duplicate of? http://stackoverflow.com/questions/8587997/sort-array-value-in-alphabetical-order?rq=1 – Daryl Gill Dec 06 '12 at 14:36

1 Answers1

1

You can try

$group = array_reduce($data, function($a,$b) { $a[$b['surname']{0}][] = $b; return $a; } );
ksort($group);

foreach($group as $id => $data)
{
    printf("<h4>%s</h4>\n",$id);
    foreach($data as $name)
    {
        printf("%s %s\n",$name['name'],$name['surname']);
    }
}

Output

<h4>B</h4>
Bill Buffalo
<h4>D</h4>
John Doe
Mark Doe

See Full Demo

Baba
  • 94,024
  • 28
  • 166
  • 217