2014-01-14 167 views
-2

我有這個陣列如何在php中根據不同的數組對數組進行排序?

array(
    'pc' => array('count'=>3), 
    'xbox' => array('count'=>3), 
    'wii' => array('count'=>3), 
    '3ds' => array('count'=>3), 
    'other' => array('count'=>3), 
) 

,我想訂購像

array(
    'wii' => array('count'=>3), 
    'xbox' => array('count'=>3), 
    'other' => array('count'=>3), 
    '3ds' => array('count'=>3), 
    'pc' => array('count'=>3), 
) 

即時通訊思想,我需要有另一個數組排序依據呢??

密鑰可能是不一樣的,所以我覺得一個isset()是爲了在一個點

編輯:標準是第二個數組鍵

什麼想法?

+2

排序的標準是什麼?我沒看到一個。 –

+1

似乎很隨機給我@JohnConde – qwertynl

+0

編輯:條件是第二個數組鍵 – Patrioticcow

回答

0

您將不得不定義一個自定義排序算法。你可以通過使用PHP的uksort()函數來做到這一點。 (與非常類似的usort()函數的區別在於它比較了陣列的鍵而不是其值)。

它看起來有點像這樣(因爲我使用匿名函數,需要PHP> = 5.3):

<?php 
$input = array(
    'pc' => array('count'=>3), 
    'xbox' => array('count'=>3), 
    'wii' => array('count'=>3), 
    '3ds' => array('count'=>3), 
    'other' => array('count'=>3), 
); 
$keyOrder = array('wii', 'xbox', 'other', '3ds', 'pc'); 

uksort($input, function($a, $b) use ($keyOrder) { 
    // Because of the "use" construct, $keyOrder will be available within 
    // this function. 
    // $a and $b will be two keys that have to be compared against each other. 

    // First, get the positions of both keys in the $keyOrder array. 
    $positionA = array_search($a, $keyOrder); 
    $positionB = array_search($b, $keyOrder); 

    // array_search() returns false if the key has not been found. As a 
    // fallback value, we will use count($keyOrder) -- so missing keys will 
    // always rank last. Set them to 0 if you want those to be first. 
    if ($positionA === false) { 
     $positionA = count($keyOrder); 
    } 
    if ($positionB === false) { 
     $positionB = count($keyOrder); 
    } 

    // To quote the PHP docs: 
    // "The comparison function must return an integer less than, equal to, or 
    // greater than zero if the first argument is considered to be 
    // respectively less than, equal to, or greater than the second." 
    return $positionA - $positionB; 
}); 

print_r($input); 
+0

似乎符合我的需求。謝謝 – Patrioticcow

相關問題