我有一個沒有排序的城鎮數組。我想按照省份的[類別] [3]和地區的[類別] [0]進行排序,並顯示每個分組省及其地區,然後顯示其下的城鎮。所以,下面的數組:php數組排序和分組
Array
(
[0] => Array
(
[name] => Name One
[id] => 1
[link] => http://mylink1.com
[category] => Array
(
[0] => Region 1
[1] => Town 7
[2] => Country
[3] => Province 2
)
)
[1] => Array
(
[name] => Name Two
[id] => 2
[link] => http://mylink2.com
[category] => Array
(
[0] => Region 1
[1] => Town
[2] => Country
[3] => Province 3
)
)
[2] => Array
(
[[name] => Name Three
[id] => 3
[link] => http://mylink3.com
[category] => Array
(
[0] => Region 1
[1] => Town 5
[2] => Country
[3] => Province 2
)
)
[6] => Array
(
[name] => Name Four
[id] => 4
[link] => http://mylink4.com
[category] => Array
(
[0] => Region 1
[1] => Town 1
[2] => Country
[3] => Province 1
)
)
)
...應該結束這樣看:
Country (all the same)
Province 1
- Region 1
- - Town 1 name, id, link
Province 2
- Region 1
- - Town 5 name, id, link
- - Town 7 name, id, link
Province 3
- Region 1
- - Town 1 name, id, link
省是主要分組因素,然後按地區分類,沒有特定的順序的城鎮,但我猜按字母順序是有道理的。
我設法按照類別使用此引用對數組進行排序:Sort Multi-dimensional Array by Value但無法想象如何進一步排序,而無需使用名稱在循環中專門引用省。即
/// shortened version..
foreach($array as $key=>$value)...
if($value == "Province 1") : do something here with these matches
... etc
任何幫助,將不勝感激。
寫一個比較函數,並用'usort()'http://php.net/manual/en/function.usort.php – alfasin 2012-08-01 22:34:46