-6

我有很多这样的用户:

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 
        )
)

我想有这样的输出:

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

我怎样才能完成这个结果?

4

1 回答 1

1

你可以试试

$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']);
    }
}

输出

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

查看完整演示

于 2012-12-06T14:36:58.363 回答