-1

I am trying to sort an array by miles.

$i = 0;
foreach($results as $key => $value)
{
    echo $results['miles'][$i] . "<br />";
    echo $results['postcode'][$i] . "<br />";
    echo $results['id'][$i] . "<br />";
    echo $results['description'][$i] . "<br />";
    echo $results['title'][$i] . "<br />";
    echo $results['thumbnail'][$i] . "<br />";
    $i++;
}

AS you can see I'm having 6 different keys here. I want to order everything by $results['miles'] in ASCENDING order.

This is my array structure:

Array ( [miles] => Array ( [0] => 0 [1] => 0 [2] => 14 [3] => 8 [4] => 8 [5] => 0 [6] => 8 [7] => 14 ) [title] => Array ( [0] => Stunning 1 Bedroom Apartment With Concierge [1] => Big Double Inc Bills+ Balcony+Free Parking [2] => Large, Sunny Flat In Willesden [3] => Brewhouse Yard EC1V [4] => Stunning 2 Double Bed Flat - City [5] => Room To Let £575 Pm Bills Included [6] => All Bills Inclusive | Gorgeous 1 Bed In The City [7] => Large Double Room In Zone 2 (Kensal Green 2 Mins) ) [id] => Array ( [0] => 187 [1] => 176 [2] => 186 [3] => 178 [4] => 179 [5] => 177 [6] => 183 [7] => 182 ) [thumbnail] => Array ( [0] => [1] => [2] => [3] => [4] => [5] => [6] => [7] => ) [postcode] => Array ( [0] => IG11 [1] => ig11 [2] => NW10 [3] => EC1 [4] => ec1 [5] => ig11 [6] => ec1 [7] => NW10 ) )

Any help would be appreciated!

C-Designer
  • 79
  • 2
  • 7

3 Answers3

0

If you can, the best way is to sort the data before it comes in to your script (if it's coming from SQL then order it there).

If you need to do it in PHP though you can use the uasort function, which allows you to define your own comparison:

function compareMiles($a, $b) {
    if ($a['miles'] == $b['miles']) {
        return 0;
    }
    return ($a['miles'] < $b['miles']) ? -1 : 1;
}

uasort($results, 'compareMiles');
Steve H
  • 898
  • 7
  • 21
0

You can use usort() function to sort it.

Parag Tyagi
  • 7,927
  • 2
  • 36
  • 44
0

Use asort() to sort an array by maintain index association.

Refer this link for details and example

Sid M
  • 4,268
  • 4
  • 27
  • 47