2011-08-08 119 views
3

multidim。陣列的樣子:通過單體陣列排列多維陣列

$arr = array(
    array(
    'id' => 'first', 
    'name' => 'John', 
    'age' => 17, 
), 

    array(
    'id' => 'second', 
    'name' => 'Mary', 
    'age' => 26, 
), 

    array(
    'id' => 'third', 
    'name' => 'Eve', 
    'age' => 21, 
), 

); 

,並決定自己如何$arr排序看起來像數組:

$sort_by = array('third', 'first', 'second');

所以我想是基於其id領域的第一個數組中的元素進行排序和第二個陣列。

在這種情況下,第一陣列應該是:

$arr = array(
    array(
    'id' => 'third', 
    'name' => 'Eve', 
    'age' => 21, 
), 

    array(
    'id' => 'first', 
    'name' => 'John', 
    'age' => 17, 
), 

    array(
    'id' => 'second', 
    'name' => 'Mary', 
    'age' => 26, 
), 


); 
+1

[基於另一個陣列的順序排序陣列子項]的可能重複(HTTP:/ /stackoverflow.com/questions/6711548/sort-array-subkey-based-on-another-arrays-order) –

回答

4
function sort_by_1d($item_1, $item_2) 
{ 
    $sort_by = array('third', 'first', 'second'); 
    $item_1_i = array_search($item_1['id'], $sort_by); 
    $item_2_i = array_search($item_2['id'], $sort_by); 
    return $item_1_i - $item_2_i; 
} 

usort($arr, 'sort_by_1d'); 
+0

+1一個聰明的解決方案:-) –

+0

非常優雅,謝謝! – luminarious