Jeroen
Jeroen

Reputation: 13257

Get highest subvalues in a 3-dimensional array using PHP

I have the following array:

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
                )

        )

)

Using PHP, I want to get an array consisting of the five values with the highest weight, like this:

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
        )

)

Of course, this could be accomplished by iterating over the array using a loop to 'flatten' the array and then sort it usort, but I think there should be an easier and faster way. However, I can't figure out what that would be.

I hope you can help me!

Upvotes: 0

Views: 85

Answers (1)

Brad Christie
Brad Christie

Reputation: 101614

Pseudo-code:

  1. Grab array_values from the original data set.
  2. Use array_merge to combine them all (essentially flatten)
  3. Use a usort and pop off first 5 elements

Upvotes: 1

Related Questions