对包含其他数组的PHP数组进行排序

时间:2014-05-20 21:24:32

标签: php arrays sorting

我在PHP中有一个数组,其中包含关联索引值,如下所示。它们与我需要做的排序无关,但我需要保留它们。 此数组中的每个值实际上是另一个数组,其中可能包含1到N个整数,按降序排序。但是,整数被写为文本(字符串)。所以初始数据看起来像这样:

[10025] => 51, 51, 43, 43, 30, 29, 28, 27, 25, 24, 22, 21
[15671] => 24, 21
[02672] => 24, 26
[76935] => 87, 72, 69, 67, 55, 43, 43, 40, 35, 33, 29

我需要通过查看每个辅助数组的最大值来对此进行排序。如果值相等,我必须查看第二个值等,所以最后我会得到这样的结果:

[76935] => 87, 72, 69, 67, 55, 43, 43, 40, 35, 33, 29
[10025] => 51, 51, 43, 43, 30, 29, 28, 27, 25, 24, 22, 21
[02672] => 24, 26
[15671] => 24, 21

arsort()默认情况下会查看每个数组中的项目数量,这些项目没有完成工作并且提升SORT_NUMERIC也不起作用 - 无法弄清楚它究竟做了什么但它并没有按照我想要的方式对数组进行排序。

我也看过array_multisort(),然而,玩弄它,我也无法获得理想的结果。

3 个答案:

答案 0 :(得分:2)

试试这个,记下uasort()函数(魔法发生的地方):

 <?php
$data = array(
    10025 => '51, 51, 43, 43, 30, 29, 28, 27, 25, 24',
    15671 => '24, 21',
    02672 => '24, 26',
    76935 => '87, 72, 69, 67, 55, 43, 43, 40, 35, 33, 29'
); //Inital data array

echo '<pre>'.print_r($data, true).'</pre>'; //Print the array as it is

uasort($data, function($a, $b) { //Sort the array using a user defined function maintaining array indices
    $aArray = explode(', ', $a); //Split the strings into proper arrays
    $bArray = explode(', ', $b);

    rsort($aArray); //Sort the proper arrays from largest to smallest
    rsort($bArray);

    return $aArray[0] > $bArray[0] ? -1 : 1; //Compare the first element in each array (because it is the largest thanks to the rsort functions)
});

echo '<pre>'.print_r($data, true).'</pre>'; //Print the array in it's new order
?>

输出:

Array
(
    [10025] => 51, 51, 43, 43, 30, 29, 28, 27, 25, 24
    [15671] => 24, 21
    [1466] => 24, 26
    [76935] => 87, 72, 69, 67, 55, 43, 43, 40, 35, 33, 29
)
Array
(
    [76935] => 87, 72, 69, 67, 55, 43, 43, 40, 35, 33, 29
    [10025] => 51, 51, 43, 43, 30, 29, 28, 27, 25, 24
    [1466] => 24, 26
    [15671] => 24, 21
)

答案 1 :(得分:0)

uasort(
    $myArray,
    function($a, $b) {
        $a = explode(',',$a);
        $b = explode(',',$a);
        $i = 0;
        while (true) {
            if (isset($a[$i]) && isset($b[$i]) && $a[$i] !== $b[0]) {
                return ($a[$i] < $b[$i]) ? -1 : 1;
            } elseif (isset($a[$i]) && !isset($b[$i])) {
                return 1;
            } elseif (isset($b[$i]) && !isset($a[$i])) {
                return -1;
            } elseif (!isset($b[$i]) && !isset($a[$i])) {
                return 0;
            }
            $i++;
        }
    }
);

答案 2 :(得分:0)

array_multisort()可以做到这一点:

$yourdata; // your assosiative array with data

$lengths = array();
foreach ($yourdata as $key => $row)
{
    $lengths[$key] = $row.length;
}
array_multisort($lengths, SORT_DESC, $yourdata);

参考网址http://www.php.net/manual/ro/function.array-multisort.php