0

I want to sort this array on basis of 'eta'.Lowest eta must come to first.

My array is :

    Array
(
    [0] => Array
        (
            [company] => Uber
            [type] => Saloon
            [eta] => 8
            [destination_required] => N
            [reject_booking_request] => N
        )

    [1] => Array
        (
            [company] => greentomato
            [type] => Saloon
            [company_rating] => 80%
            [eta] => 10
            [destination_required] => N
            [reject_booking_request] => N
        )

    [2] => Array
        (
            [company] => CATALINA
            [type] => Exec
            [eta] => 12
            [destination_required] => Y
            [reject_booking_request] => N
        )

    [3] => Array
        (
            [company] => Uber
            [type] => Exec
            [eta] => 15
            [destination_required] => N
            [reject_booking_request] => N
        )

    [4] => Array
        (
            [company] => Hailo
            [type] => Taxi
            [eta] => 1
            [destination_required] => Y
            [reject_booking_request] => Y
        )

)

I want to sort this array on basis of 'eta'.Lowest eta must come to first.

I tried to use this :

 $result = Set::sort($array, '{n}', 'asc');

But it gives some error.

Debasis
  • 201
  • 3
  • 9

3 Answers3

2

You can use usort:

usort($yourArray, function($a, $b) {
    return $a['eta'] - $b['eta'];
});

Usort allows the definition of a custom sortation callback function as the second parameter. Inside the body of this method you can define your comparison algorithm.

If the method returns a negative number it will move the $b variable down the array, returning a positive number will move $b up the array and return 0 keeps $b in the same place.

We have defined an inline callback method for simplicity sake.

phpPhil
  • 906
  • 1
  • 9
  • 28
  • While this may answer the question it’s always a good idea to put some text in your answer to explain what you're doing. Read [how to write a good answer](http://stackoverflow.com/help/how-to-answer). – Jørgen R Feb 27 '15 at 11:44
  • Thanks. I added some additional explanation. – phpPhil Feb 27 '15 at 13:03
1

I did that in cakephp :

My Ans is :

Hash::sort($array, '{n}.eta', 'asc');
Debasis
  • 201
  • 3
  • 9
0

You can use array multisort function.

Follow the link for more information. http://php.net/manual/en/function.array-multisort.php