数组中的多个排序

时间:2012-07-29 08:40:25

标签: php arrays multidimensional-array

我有以下数组:

Array
(
[0] => Array
    (
        [note] => test
        [year] => 2011
        [type] => football
    )

[1] => Array
    (
        [note] => test1
        [year] => 2010
        [type] => basket
    )

[2] => Array
    (
        [note] => test2
        [year] => 2012
        [type] => football
    )

[3] => Array
    (
        [note] => test3
        [year] => 2009
        [type] => basket
    )

[4] => Array
    (
        [note] => test4
        [year] => 2010
        [type] => football
    )

)

我想首先按类型对另一个数组进行排序:

例如:$sort = array('football','basket');

之后一年。

我该怎么做?

感谢。

期望的输出应该是:

Array
(
[2] => Array
    (
        [note] => test2
        [year] => 2012
        [type] => football
    )
[0] => Array
    (
        [note] => test
        [year] => 2011
        [type] => football
    )
[4] => Array
    (
        [note] => test4
        [year] => 2010
        [type] => football
    )

[1] => Array
    (
        [note] => test1
        [year] => 2010
        [type] => basket
    )

[3] => Array
    (
        [note] => test3
        [year] => 2009
        [type] => basket
    )

)

我不介意我们重置索引值。

感谢。

3 个答案:

答案 0 :(得分:4)

在按原样运行时需要支持闭包的PHP版本

您的辅助数组可以在排序本身之外定义。如果你不能支持闭包,那么这可以直接放入排序例程。

$sortBy = array('football', 'basket');

排序例程。

如果类型相同,则按年份排序,否则按$sortBy数组中的类型排序。

usort($a, function($a, $b) use ($sortBy) {
    if ($a['type'] == $b['type']) {
        return ($b['year'] - $a['year']);
    }
    $typeOrder = array_flip($sortBy);
    return $typeOrder[$a['type']] - $typeOrder[$b['type']];
});

答案 1 :(得分:2)

使用array_multisort。假设您的数组是$arr

foreach($arr as $key=>$row) {
    $type[$key] = $row['type'];
    $year[$key] = $row['year'];
}
array_multisort($type, SORT_ASC, $year, SORT_ASC, $arr);

要使用指定类型顺序的其他数组,您可以执行以下操作:

$sortBy = array('football','basket');
foreach($arr as $key=>$row) {
    $type[$key] = array_search($row['type'],$sortBy);
    $year[$key] = $row['year'];
}
array_multisort($type, SORT_ASC, $year, SORT_ASC, $arr);

示例链接:

http://codepad.org/qhZCpbZE

答案 2 :(得分:1)

使用usort

function byType($a, $b)
{
    if ($a['type'] == $b['type']) {
        return 0;
    }

    foreach(array('football','basket') as $type) {
        if ($a['type']=$type) return -1;
        if ($b['type']=$type) return 1;
    }

    return 0;
}


function byYear($a, $b)
{
    if ($a['year'] == $b['year']) {
        return 0;
    }
    return ($a['year'] < $b['year']) ? -1 : 1;
}

usort($array,"byType");
usort($array,"byYear");