5

我有以下数组:

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
    )

)

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

谢谢。

4

3 回答 3

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']];
});
于 2012-07-29T09:04:54.383 回答
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

于 2012-07-29T08:54:42.310 回答
1

使用排序

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");
于 2012-07-29T08:49:46.537 回答