按内部值排序多维数组,需要保存密钥

时间:2016-06-23 05:09:26

标签: php arrays sorting multidimensional-array

我的数组是

Array
(
    [0] => Array
        (
            [package] => Bag
            [qty] => 10.00
            [price] => 19.00

        )

    [1] => Array
        (
            [package] =>  kgs
            [qty] => 1.00
            [price] => 2.00

        )

    [2] => Array
        (
            [package] => Bag
            [qty] => 25.00
            [price] => 50.00

        )

)

我需要根据价格上升值对此数组进行排序。我使用 usort 。我的代码看起来像

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

然后我得到了结果数组

  Array
(
    [0] => Array
        (
            [package] =>  kgs
            [qty] => 1.00
            [price] => 2.00

        )

    [1] => Array
        (
            [package] => Bag
            [qty] => 10.00
            [price] => 19.00

        )

    [2] => Array
        (
            [package] => Bag
            [qty] => 25.00
            [price] => 50.00

        )

)

但我的实际需求是通过保留键来获得结果。也就是说,

Array
(
    [1] => Array
        (
            [package] =>  kgs
            [qty] => 1.00
            [price] => 2.00

        )

    [0] => Array
        (
            [package] => Bag
            [qty] => 10.00
            [price] => 19.00

        )

    [2] => Array
        (
            [package] => Bag
            [qty] => 25.00
            [price] => 50.00

        )

)

我该怎么办?请帮帮我。

0 个答案:

没有答案