2012-04-03 68 views
22

可能重複:
how to sort a multidemensional array by an inner key
How to sort an array of arrays in php?PHP按字段排序數組?

我怎樣纔能有點像數組:$array[$i]['title'];

陣列結構可能是這樣的:

array[0](
'id' => 321, 
'title' => 'Some Title', 
'slug' => 'some-title', 
'author' => 'Some Author', 
'author_slug' => 'some-author'); 

array[1](
'id' => 123, 
'title' => 'Another Title', 
'slug' => 'another-title', 
'author' => 'Another Author', 
'author_slug' => 'another-author'); 

所以數據顯示在ASC訂單基於標題字段在數組中?

+0

邁克爾:蒂姆只是在幫助。首先進行搜索是這裏的一個先決條件,我們可以得到一個似乎並未先搜索/嘗試的提問者。 – halfer 2012-04-03 19:39:02

回答

68

使用usort爲此目的明確構建。

function cmp($a, $b) 
{ 
    return strcmp($a["title"], $b["title"]); 
} 

usort($array, "cmp"); 
+11

您也可以乘以-1來逆轉排序,只是給所有需要這樣做的人提供了一個供參考。 – 2014-02-13 21:30:26

+14

從PHP 5.3開始,您可以使用匿名函數,如果您位於名稱空間中的類中,這非常有幫助: 'usort($ domain_array,function($ a,$ b) { return strcmp($ a [名稱「],$ b [」名稱「]); }); ' – 2016-10-11 08:35:27

+1

只需添加一點到@GabiLee,如果您希望搜索字段基於您已設置的某個變量進行動態設置,請嘗試以下操作:usort($ domain_array,function($ a,$ b)use($ searchField){return strcmp($ a [$ searchField],$ b [$ searchField]);});例如,在用戶可以選擇要排序的字段的網頁上,這可能很有用。 – stealthysnacks 2017-02-14 22:26:27