2012-04-18 35 views
1

我有這個數組,它已經按'name'ASC排序。使用其中一個值對多維數組進行排序,同時遵守其順序php

array 
    0 => 
    array 
     'id' => '4' 
     'name' => 'iPad' 
     'games' => 5 
    1 => 
    array 
     'id' => '5' 
     'name' => 'iPhone' 
     'games' => 5 
    2 => 
    array 
     'id' => '6' 
     'name' => 'Nintendo DS' 
     'games' => 5 
    3 => 
    array 
     'id' => '1' 
     'name' => 'Playstation 2' 
     'games' => 2 
    4 => 
    array 
     'id' => '7' 
     'name' => 'Playstation 3' 
     'games' => 2 
    5 => 
    array 
     'id' => '7' 
     'name' => 'Xbox 360' 
     'games' => 1 

如果'遊戲'的值相同,我想按'遊戲'的值排序,同時尊重排序'名稱'的順序。

結果應該是這樣的:

array 
    0 => 
    array 
     'id' => '7' 
     'name' => 'Xbox 360' 
     'games' => 1 
    1 => 
    array 
     'id' => '1' 
     'name' => 'Playstation 2' 
     'games' => 2 
    2 => 
    array 
     'id' => '7' 
     'name' => 'Playstation 3' 
     'games' => 2 
    3 => 
    array 
     'id' => '4' 
     'name' => 'iPad' 
     'games' => 5 
    4 => 
    array 
     'id' => '5' 
     'name' => 'iPhone' 
     'games' => 5 
    5 => 
    array 
     'id' => '6' 
     'name' => 'iPod Touch' 
     'games' => 5 

我幾乎嘗試了所有種類的功能和用戶自定義的比較函數,但找不到合適的人。

如果可能的話,如果我想要'遊戲'DESC,並且如果遊戲的價值是相同的,那麼在維護排序後的'名稱'ASC時該如何處理呢?例如:

array 
    0 => 
    array 
     'id' => '6' 
     'name' => 'Nintendo DS' 
     'games' => 5 
    1 => 
    array 
     'id' => '5' 
     'name' => 'iPhone' 
     'games' => 5 
    2 => 
    array 
     'id' => '4' 
     'name' => 'iPad' 
     'games' => 5 
    3 => 
    array 
     'id' => '1' 
     'name' => 'Playstation 2' 
     'games' => 2 
    4 => 
    array 
     'id' => '7' 
     'name' => 'Playstation 3' 
     'games' => 2 
    5 => 
    array 
     'id' => '7' 
     'name' => 'Xbox 360' 
     'games' => 1 
+2

你使用mysql來拉數據嗎?你可以使用2順序而不是從php – 2012-04-18 01:37:30

回答

2
usort($array, function ($a, $b) { 
    if ($a['games'] == $b['games']) { 
     return strcmp($a['name'], $b['name']); 
    } else { 
     return $a['games'] - $b['games']; 
    } 
}); 
+0

我可能有ASC與DESC混合在這裏,我總是不能讓他們直...如果是這樣,反轉'$ a'和'$ b'。 – deceze 2012-04-18 01:48:23

+0

It Works!我還用'strcasecmp'取代了'strcmp',因爲iPhone和iPod中的小寫'i'會擾亂訂單。謝謝! – user1105430 2012-04-18 02:02:59

0

有使用自定義的比較函數的其它方法,但是最簡單的方法是用array_multisort

首先使用您想要對數組進行排序的鍵創建數組。然後將這些陣列的排序參數提供給array_multisort

// first collect the sorting keys 
// ensure that $thearray[$n]['key'] corresponds to $sortkey[$n] 
$games = array(); 
$name = array(); 
foreach ($thearray as $item) { 
    $games = $item['games']; 
    $name = $item['name']; 
} 

// now sort 
array_multisort($games, SORT_NUMERIC, SORT_ASC, 
       $name, SORT_STRING, SORT_ASC, 
       $thearray); 
// $thearray is now sorted first by games, then by name. 
相關問題