PHP - 使用array_multisort

时间:2015-07-29 20:01:20

标签: php array-multisort

我有这个多维数组

Array
(
    [0] => Array
        (
            [at] => 0
            [bt] => 9
        )

    [1] => Array
        (
            [at] => 3
            [bt] => 5
        )

    [2] => Array
        (
            [at] => 0
            [bt] => 3
        )

)

我想按键排序" at"所以我试过这段代码

//$process = array() given above

$p = array();

foreach ($process as $key => $row) {
        $p[$key] = $row['at'];
}

array_multisort($p, SORT_NUMERIC, SORT_ASC, $process);

我得到了这个结果

Array
(
    [0] => Array
        (
            [at] => 0
            [bt] => 3
        )

    [1] => Array
        (
            [at] => 0
            [bt] => 9
        )

    [2] => Array
        (
            [at] => 3
            [bt] => 5
        )

)

它排序" at"但它也排序" bt"。

如何在键上排序此数组" at" ONLY?

像这样:

Array
(
    [0] => Array
        (
            [at] => 0
            [bt] => 9
        )

    [1] => Array
        (
            [at] => 0
            [bt] => 3
        )

    [2] => Array
        (
            [at] => 3
            [bt] => 5
        )

)

谢谢。

修改

关于Mathieu Lescaudron的答案

当我在阵列上只有这个时,

Array
(
    [0] => Array
        (
            [at] => 0
            [bt] => 9
        )

    [1] => Array
        (
            [at] => 0
            [bt] => 3
        )
)

如何防止它排序,因为我只想按键排序" at"。没有什么可以排序,因为他们都是0。

1 个答案:

答案 0 :(得分:2)

使用usort

$array = array(
            array('at' => 0, 'bt' => 9),
            array('at' => 3, 'bt' => 5),
            array('at' => 0, 'bt' => 3)
        );

usort($array, function($a, $b) {
    return $a['at'] - $b['at'];
});

var_dump($array);

Try it on Php online