Sort object array

Asked

Viewed 3,650 times

3

I have as a result of a query to the database the following data:

Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [nome] => Pizzaria 1
            [latitude] => -8.12044775643893
            [longitude] => -35.025825550000036
            [distancia] => 3800
        )

    [1] => stdClass Object
        (
            [id] => 2
            [nome] => Pizzaria 2
            [latitude] => -7.90856162499827
            [longitude] => -34.91269575000001
            [distancia] => 1500
        )

    [2] => stdClass Object
        (
            [id] => 3
            [nome] => Pizzaria 3
            [latitude] => -8.12044775643893
            [longitude] => -35.025825550000036
            [distancia] => 2000
        )
)

Only I’m adding the entrance distance Then it doesn’t exist in the bank. It serves to store the value of a distance calculation, in meters, done when the user enters the page so that it is ordered from the nearest to the farthest.

My question is how do I sort this array of objects so that the distance is in ascending order?

1 answer

7

For these and other cases, usort() is who you seek.

However, slightly different from the manual examples, you should inform the properties that will be used as a basis for comparison.

It’s not much different from the first example, see:

usort(

    $data,

     function( $a, $b ) {

         if( $a -> distancia == $b -> distancia ) return 0;

         return ( ( $a  -> distancia < $b  -> distancia ) ? -1 : 1 );
     }
);

The exit as expected:

Array
(
    [0] => stdClass Object
        (
            [id] => 2
            [nome] => Pizzaria 2
            [latitude] => -7.9085616249983
            [longitude] => -34.91269575
            [distancia] => 1500
        )

    [1] => stdClass Object
        (
            [id] => 3
            [nome] => Pizzaria 3
            [latitude] => -8.1204477564389
            [longitude] => -35.02582555
            [distancia] => 2000
        )

    [2] => stdClass Object
        (
            [id] => 1
            [nome] => Pizzaria 1
            [latitude] => -8.1204477564389
            [longitude] => -35.02582555
            [distancia] => 3800
        )

)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.