使用PHP获取三维数组中的最高子值

时间:2011-08-19 19:37:17

标签: php arrays sorting

我有以下数组:

Array
(
    [medium_priority] => Array
        (
            [0] => Array
                (
                    [module] => a
                    [block] => b
                    [message] => c
                    [weight] => 60
                )

        )

    [high_priority] => Array
        (
            [0] => Array
                (
                    [module] => a
                    [block] => b
                    [message] => c
                    [weight] => 95
                )

            [1] => Array
                (
                    [module] => a
                    [block] => b
                    [message] => c
                    [weight] => 85
                )

            [2] => Array
                (
                    [module] => a
                    [block] => b
                    [message] => c
                    [weight] => 80
                )

        )

    [low_priority] => Array
        (
            [0] => Array
                (
                    [module] => a
                    [block] => b
                    [message] => c
                    [weight] => 20
                )

            [1] => Array
                (
                    [module] => a
                    [block] => b
                    [message] => c
                    [weight] => 30
                )

        )

)

使用PHP,我希望得到一个由最高weight的五个值组成的数组,如下所示:

Array
(               
    [0] => Array
        (
            [module] => a
            [block] => b
            [message] => c
            [weight] => 95
        )

    [1] => Array
        (
            [module] => a
            [block] => b
            [message] => c
            [weight] => 85
        )

    [2] => Array
        (
            [module] => a
            [block] => b
            [message] => c
            [weight] => 80
        )               

    [3] => Array
        (
            [module] => a
            [block] => b
            [message] => c
            [weight] => 60
        )

    [4] => Array
        (
            [module] => a
            [block] => b
            [message] => c
            [weight] => 30
        )

)

当然,这可以通过使用循环遍历数组以“展平”数组然后对其进行排序usort来实现,但我认为应该有一种更简单,更快捷的方法。 但是,我无法弄清楚会是什么。

我希望你能帮助我!

1 个答案:

答案 0 :(得分:1)

的伪代码:

  1. 从原始数据集中抓取array_values
  2. 使用array_merge将它们全部合并(基本上是扁平的)
  3. 使用usort并弹出前5个元素