I have created the following array in PHP with help of the Google Distance Matrix API.
Now I need to compare the [distance
] field, get the lowest value and save the key of the array in a variable. How do I do this? I looked at min()
but this doesn't seem to work with multiple arrays.
Array
(
[utrecht_cs] => Array
(
[name] => utrecht_cs
[address] => 3511 AX Utrecht, Netherlands
[distance] => 95
)
[groningen_cs] => Array
(
[name] => groningen_cs
[address] => 9726 AC Groningen, Netherlands
[distance] => 102.47
)
[zwolle_cs] => Array
(
[name] => zwolle_cs
[address] => 8011 CW Zwolle, Netherlands
[distance] => 2.54
)
)
You could use uasort()
to sort your array. Then, you could get the first key using key()
.
$array = array(
'utrecht_cs' => array(
'name' => 'utrecht_cs',
'address' => '3511 AX Utrecht, Netherlands',
'distance' => 95
),
'groningen_cs' => array(
'name' => 'groningen_cs',
'address' => '9726 AC Groningen, Netherlands',
'distance' => '102.47'
),
'zwolle_cs' => array(
'name' => 'zwolle_cs',
'address' => '8011 CW Zwolle, Netherlands',
'distance' => '2.54'
)
);
uasort($array, function($a, $b) { return $a['distance'] <=> $b['distance']; });
$first_key = key($array);
Output:
zwolle_cs
You can also use (for PHP version before 7.0):
uasort($array, function($a, $b) {
return $a['distance'] < $b['distance'] ? -1 : 1;
});
You want to use usort
to sort your multidimensional array.
http://php.net/manual/en/function.usort.php
function sortNumbers($a, $b)
{
return $a['distance'] <=> $b['distance'];
}
usort($yourArray,'sortNumbers');
Read this for more info https://delboy1978uk.wordpress.com/2012/09/19/sorting-multidimensional-arrays-using-php/
An alternative sorting. Extract the distance
column from the array and sort on that, sorting the original array based that:
array_multisort(array_column($array, 'distance'), $array);
$result = key($array);