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 the arrays in the hash by distance.
Sorting a multidimensional array by element containing date. Use the usort() function to sort the array. The usort() function is PHP builtin function that sorts a given array using user-defined comparison function.
Use sorted() with a lambda function to sort a multidimensional list by column. Call sorted(iterable, key=None) with key set to a lambda function of syntax lambda x: x[i] to sort a multidimensional list iterable by the i th element in each inner list x .
The arsort() function sorts an associative array in descending order, according to the value. Tip: Use the asort() function to sort an associative array in ascending order, according to the value. Tip: Use the krsort() function to sort an associative array in descending order, according to the key.
array_multisort() can be used to sort several arrays at once, or a multi-dimensional array by one or more dimensions. Associative (string) keys will be maintained, but numeric keys will be re-indexed.
You need to extract all the distances first, 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 you want the shortest distances first, otherwise change the SORT_ASC
to SORT_DESC
If you want to avoid the looping you can use the array_column
function to achieve your target.
For Example,
You want to sort below array with distance sort
$arr = array(
0 => array( 'lat' => 34, 'distance' => 332.08 ),
1 => array( 'lat' => 34, 'distance' => 5 ),
2 => array( 'lat' => 34, 'distance' => 34 )
);
Using below single line your array will be sort by distance
array_multisort( array_column( $arr, 'distance' ), SORT_ASC, SORT_NUMERIC, $arr );
Now, $arr contain with sorted array by distance
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With