PHP在保持数组键的同时排序维关联数组

时间:2015-11-13 07:40:40

标签: php usort

我是这样的阵列..

<?php

$a = array(
    "2" => array(
        "v" => 1
    ),
    "3" => array(
        "v" => 2
    )
);

usort($a, function($a, $b)
{
    return $a['v'] < $b['v'];
});

当我使用usortv的值排序时,它会返回

Array
(
    [0] => Array
        (
            [v] => 2
        )

    [1] => Array
        (
            [v] => 1
        )

)

但我希望密钥不被修改,例如

Array
(
    [3] => Array
        (
            [v] => 2
        )

    [2] => Array
        (
            [v] => 1
        )

)

有可能吗?

1 个答案:

答案 0 :(得分:0)

使用uasort保留密钥

<?php

$a = array(
    "2" => array(
        "v" => 1
    ),
    "3" => array(
        "v" => 2
    )
);

uasort($a, function($a, $b)
{
    return $a['v'] < $b['v'];
});