使用两个值对数组进行排序

时间:2014-05-29 13:17:00

标签: php arrays sorting

我正在尝试使用两个值(order,sub_order)对数组进行排序,以便它们是1.1,1.2,2.1,2.1等命令。

下面是现在的数组示例,第二个是按order和sub_order值正确排序的数组。

Array
(
    [0] => Array
        (
            [id] => 1
            [order] => 1
            [sub_order] => 2
            [title] => Blah 
        )

    [1] => Array
        (
            [id] => 3
            [order] => 2
            [sub_order] => 2
            [title] => Blah 
        )

    [2] => Array
        (
            [id] => 2
            [order] => 1
            [sub_order] => 1
            [title] => Blah 
        )

    [3] => Array
        (
            [id] => 4
            [order] => 2
            [sub_order] => 1
            [title] => Blah 
        )

)

正确订购......

Array
(
    [0] => Array
        (
            [id] => 2
            [order] => 1
            [sub_order] => 1
            [title] => Blah 
        )

    [1] => Array
        (
            [id] => 1
            [order] => 1
            [sub_order] => 2
            [title] => Blah 
        )

    [2] => Array
        (
            [id] => 4
            [order] => 2
            [sub_order] => 1
            [title] => Blah 
        )

    [3] => Array
        (
            [id] => 3
            [order] => 2
            [sub_order] => 2
            [title] => Blah 
        )

)

任何帮助都会很棒。

1 个答案:

答案 0 :(得分:3)

使用usort

usort($array, "order_sub_order_sort");
function order_sub_order_sort($a, $b) {
    if ($a["order"] != $b["order"]) {
        return $a["order"] - $b["order"];
    }
    return $a["sub_order"] - $b["sub_order"]
}

如果您想要反过来排序,请更改$a-$b的{​​{1}}。我总是忘记哪个是上升的,哪个是下降的。