sort a multidimensional array using array_multisort

I have this array

Array ( [0] => Array ( [brand] => blah blah [location] => blah blah [address] => blah blah [city] => blah blah [state] => CA [zip] => 90210 [country] => USA [phone] => 555-1212 [long] => -111 [lat] => 34 [distance] => 3.08 ) [1] => Array ( [brand] => blah blah [location] => blah blah [address] => blah blah [city] => blah blah [state] => CA [zip] => 90210 [country] => USA [phone] => 555-1212 [long] => -111 [lat] => 34 [distance] => 5 ) . . . } 

I want to be able to sort arrays in a hash by distance.

+12
sorting arrays php
source share
4 answers

First you need to extract all the distances, and then pass both the distance and the data to the function. As shown in Example 3 in the array_multisort documentation.

 foreach ($data as $key => $row) { $distance[$key] = $row['distance']; } array_multisort($distance, SORT_ASC, $data); 

This assumes that you want the shortest distances first, otherwise change SORT_ASC to SORT_DESC

+22
source share

If you want to avoid looping, you can use the array_column function to achieve your goal. For example,

You want to sort the array below with sorting by distance

 $arr = array( 0 => array( 'lat' => 34, 'distance' => 332.08 ), 1 => array( 'lat' => 34, 'distance' => 5 ), 2 => array( 'lat' => 34, 'distance' => 34 ) ); 

Using one line below, your array will be sorted by distance

 array_multisort( array_column( $arr, 'distance' ), SORT_ASC, SORT_NUMERIC, $arr ); 

Now $ arr contains a sorted array by distance

+5
source share

Usage may use usort ;

 function cmpDistance($a, $b) { return ($a['distance'] - $b['distance']); } usort($array, "cmpDistance"); 
+2
source share

This code helps sort a multidimensional array using array_multisort ()

  $param_dt = array(); foreach ($data_set as $key => $row) { if(isset($row['params']['priority'])) { $param_dt[$key] = $row['params']['priority']; } else { $param_dt[$key] = -2; // if priority key is not set for this array - it first out } } array_multisort($param_dt, SORT_ASC,SORT_NUMERIC, $data_set); 

Now $data_set has a sorted list of items.

+1
source share

All Articles