按2列排序多维数组

时间:2012-04-25 12:36:06

标签: php arrays sorting multidimensional-array

我想通过其中一个列对2D数组进行排序...例如:

$a = array(
    'user4' => array('name' => 'u4', 'payment' => 1000, 'time' => 5000),
    'user2' => array('name' => 'u2', 'payment' => 2000, 'time' => 5000),
    'user3' => array('name' => 'u3', 'payment' => 2000, 'time' => 3000),
);

我希望按paymentDESC)和timeASC)对其进行排序。 所以排序的数组应该是这样的:

$a = array(
    'user3' => array('name' => 'u3', 'payment' => 2000, 'time' => 3000),
    'user2' => array('name' => 'u2', 'payment' => 2000, 'time' => 5000),
    'user4' => array('name' => 'u4', 'payment' => 1000, 'time' => 5000),
);

怎么做? 谢谢,


我找到了解决方案:

    foreach ($a as $key => $row) {
        $payment[$key]  = $row['payment'];
        $time[$key] = $row['time'];
    }

    array_multisort($payment, SORT_DESC, $time, SORT_ASC, $a);

来源:http://php.net/manual/en/function.array-multisort.php

2 个答案:

答案 0 :(得分:2)

您可以使用usort

$arr = array(
    'user4' => array('name' => 'u4', 'payment' => 1000, 'time' => 5000),
    'user2' => array('name' => 'u2', 'payment' => 2000, 'time' => 5000),
    'user3' => array('name' => 'u3', 'payment' => 2000, 'time' => 3000),
);

function mySort($a,$b) {
    if ($a['payment'] == $b['payment']) {
        return $a['time'] - $b['time'];
    } else {
        return $b['payment'] - $a['payment'];
    }
}
usort($arr, 'mySort');
print_r($arr);

<强>输出:

Array
(
    [0] => Array
        (
            [name] => u3
            [payment] => 2000
            [time] => 3000
        )

    [1] => Array
        (
            [name] => u2
            [payment] => 2000
            [time] => 5000
        )

    [2] => Array
        (
            [name] => u4
            [payment] => 1000
            [time] => 5000
        )

)

答案 1 :(得分:0)

Yes usort就是答案。在我看来,PHP array_multisort表现得很奇怪,强迫你将自然格式化的表数据分解成单独的数组。

这是一个用于表格数据格式化多维数组的多列排序的简单解决方案。

http://pastebin.com/9vCy1jxH