2016-07-30 58 views
0

排序多維數組我有數組這樣,由多個值

Array 
(
    [341] => Array 
    (
     [id] => 2034 
     [name] => Basic 
     [file] => 577688a31d889.svg 
     [order] => 12 
    ) 

    [342] => Array 
    (
     [id] => 2065 
     [name] => Bold 
     [file] => 579af7d384970.svg 
     [order] => 0 
    ) 

    [344] => Array 
    (
     [id] => 2036 
     [name] => Modern 
     [file] => 577688a37fe1b.svg 
     [order] => 10 
    ) 

    [1869] => Array 
    (
     [id] => 2066 
     [name] => Professional 
     [file] => 579af7d3c0774.svg 
     [order] => 0 
    ) 

    [335] => Array 
    (
     [id] => 2033 
     [name] => Favourites 
     [file] => 577688a2e0502.svg 
     [order] => 0 
    ) 

    [1870] => Array 
    (
     [id] => 2067 
     [name] => traditional 
     [file] => 579af7d3f231a.svg 
     [order] => 0 
    ) 
) 

我想desc的順序排序的。但是,如果訂單相同,則按照其名稱asc進行分類。我也想保留數組的關鍵。我嘗試了一些解決方案,但對我來說效果並不好,在某些解決方案中,它放棄了關鍵。

usort($data, function($a, $b) { 
    $rdiff = $a['order'] - $b['order']; 
    if ($rdiff) return $rdiff; 
    return $a['name'] - $b['name']; 
}); 

所以根據給定的陣列中,輸出應該是這樣的, 341, 344, 342 335, 1869, 1870

+0

@NanaPartykar我更新了我的問題 – hemsbhardiya

回答

2

使用uasortstrcasecmp功能的解決方案:

// $arr is your initial array 
uasort($arr, function ($a, $b) { 
    if ($a['order'] == $b['order']){ 
     return strcasecmp($a['name'], $b['name']); 
    } else { 
     return $b['order'] - $a['order']; 
    } 
}); 

print_r($arr); 

DEMO link