2012-12-06 206 views
-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 

我怎樣才能做到這一點的結果?

+1

讀了關於'usort()'功能,並在此右側列出的所有類似的問題頁。 – SDC

+0

我不需要對數組進行排序,而只需將姓氏的第一個字母組合在一起。 – Pennywise83

+0

可能重複? http://stackoverflow.com/questions/8587997/sort-array-value-in-alphabetical-order?rq=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 

See Full Demo

+0

** Downvoter **你能給出一個理由嗎? – Baba