Sort array of objects [duplicate]

1

I have the following data as a result of querying the database:

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
        )
)

I'm just adding the distance entry later because it does not exist in the database. It is used to store the value of a distance calculation, in meters, when the user enters the page to be sorted 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?

    
asked by anonymous 29.05.2014 / 20:22

1 answer

5

For these and other cases, usort () is who you are looking for.

However, slightly different from the examples in the manual, you should tell 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 output, 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
        )

)
    
29.05.2014 / 20:40