Search code examples
phparrayssortingmultidimensional-arraynatural-sort

Naturally sort an array of objects by column value


I want to sort the values by ascending order.

I tried ksort, and other sorting examples.

Array
(
    [0] => stdClass Object
        (
            [tenure] => 1 year to less than 2 years
        )

    [1] => stdClass Object
        (
            [tenure] => 10 years to less than 15 years
        )

    [2] => stdClass Object
        (
            [tenure] => 15 years or more
        )

    [3] => stdClass Object
        (
            [tenure] => 2 years to less than 5 years
        )

    [4] => stdClass Object
        (
            [tenure] => 5 years to less than 10 years
        )

)

I want to sort the tenure values of the above array.


Solution

  • You can use core array_multisort

    array_multisort(array_column($array, 'tenure'),   
    SORT_ASC, SORT_NATURAL, $array);
    

    https://3v4l.org/cXNQH.