Skip to content
Advertisement

How to take array object from the array object based on the highest value by a column in php

I have the following array, and each element of the array has a priority element. Based on the maximum priority value how can we generate the new array?

Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [name] => Main Category 1
            [updated] => 2020-01-14 14:13:30
            [priority] => 1
        )

    [1] => stdClass Object
        (
            [id] => 2
            [name] => Main Category 2
            [updated] => 2020-01-14 17:19:35
            [priority] => 2
        )

    [2] => stdClass Object
        (
            [id] => 3
            [name] => Category 3
            [updated] => 2020-01-14 17:42:23
            [priority] => 3
        )

)

Thus the highest priority value here 3. So, the result array will be like the following. Can you help me please. Thank you in advance.

Array
    (
        [0] => stdClass Object
            (
                [id] => 3
                [name] => Category 3
                [updated] => 2020-01-14 17:42:23
                [priority] => 3
            )

    )

Advertisement

Answer

You could use usort to sort your array by priority descending, and then make an array of the [0] element:

usort($array, function ($a, $b) { return $b->priority - $a->priority; });
print_r(array($array[0]));

Output:

Array
(
    [0] => stdClass Object
        (
            [id] => 3
            [name] => Category3
            [updated] => 2020-01-1417:42:23
            [priority] => 3
        )
)

Demo on 3v4l.org

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement