2014-01-14 106 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

相关问题