需要根据特定的键值php对一组数组进行排序

时间:2017-01-27 07:44:47

标签: php arrays multidimensional-array

我需要帮助排序一个数组,该数组具有不同的组,每个组具有相同的值。我想按降序对组进行排序。请看下面的内容:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [name] => rose
                    [price] => 3
                )

            [1] => Array
                (
                    [name] => daisy
                    [price] => 3
                )

            [2] => Array
                (
                    [name] => orchid
                    [price] => 3
                )

        )
[1] => Array
    (
        [0] => Array
            (
                [name] => rose
                [price] => 1
            )

        [1] => Array
            (
                [name] => daisy
                [price] => 1
            )

        [2] => Array
            (
                [name] => orchid
                [price] => 1
            )

    )

[2] => Array
    (
        [0] => Array
            (
                [name] => rose
                [price] => 2
            )

        [1] => Array
            (
                [name] => daisy
                [price] => 2
            )

        [2] => Array
            (
                [name] => orchid
                [price] => 2
            )

    )

)

我希望它按照这样排序:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [name] => rose
                    [price] => 3
                )

            [1] => Array
                (
                    [name] => daisy
                    [price] => 3
                )

            [2] => Array
                (
                    [name] => orchid
                    [price] => 3
                )

        )

[1] => Array
    (
        [0] => Array
            (
                [name] => rose
                [price] => 2
            )

        [1] => Array
            (
                [name] => daisy
                [price] => 2
            )

        [2] => Array
            (
                [name] => orchid
                [price] => 2
            )

    )

[2] => Array
    (
        [0] => Array
            (
                [name] => rose
                [price] => 1
            )

        [1] => Array
            (
                [name] => daisy
                [price] => 1
            )

        [2] => Array
            (
                [name] => orchid
                [price] => 1
            )

    )

)

注意我有一大群人。但这只是获得一个想法的一部分。

从上面可以理解,我希望上面的数组按价格键按降序排序。

提前致谢!

1 个答案:

答案 0 :(得分:0)

试一试。

uasort($array, function ($a, $b) {
    $price_a = array_values($a)[0]['price'];
    $price_b = array_values($b)[0]['price'];

    return $price_b - $price_a;
});

注意:如果group为空,则会出现错误。