我有一个这样的数组:
Array
(
[0] => Array
(
[ID] => 85597
[DISTANCE] => 14916.204333483
)
[1] => Array
(
[ID] => 85598
[DISTANCE] => 71.712470188284
)
[2] => Array
(
[ID] => 85599
[DISTANCE] => 14130.470174227
)
[3] => Array
(
[ID] => 85600
[DISTANCE] => 14917.670508146
)
)
我想返回最低[DISTANCE]的[ID]。
我尝试使用min(),但这似乎只是比较[ID]值。
有什么想法吗?
答案 0 :(得分:1)
$min = PHP_INT_MAX;
foreach($array as $value){
if($value['DISTANCE'] < $min){
$minId = $value['ID'];
$min = $value['DISTANCE'];
}
}
$minId
将是最低距离的ID
答案 1 :(得分:0)
尝试类似:
foreach($array as $a){
$newArray[$a['ID']] = $a['DISTANCE'];
}
$min = min(array_values($newArray));
function showId($least){
foreach($newArray as $i => $v){
if($least === $v){
return $i;
}
}
}
echo showId($min);
答案 2 :(得分:0)
认为这会让你开心: - )
$data = array(
array('id' => 1, 'distance' => rand(1,100000)),
array('id' => 2, 'distance' => rand(1,100000)),
array('id' => 3, 'distance' => rand(1,100000)),
array('id' => 4, 'distance' => rand(1,100000)),
array('id' => 5, 'distance' => rand(1,100000)),
array('id' => 6, 'distance' => rand(1,100000)),
array('id' => 7, 'distance' => rand(1,100000)),
array('id' => 8, 'distance' => rand(1,100000)),
);
echo "--raw data--\n";
var_dump($data);
function distanceSorter($a, $b) {
return $a['distance'] - $b['distance'];
}
usort($data, 'distanceSorter');
echo "--sorted data--\n";
var_dump($data);
echo "--grab first result ( lowest )--\n";
var_dump($data[0]);
GIVES
--raw data--
array(8) {
[0]=>
array(2) {
["id"]=>
int(1)
["distance"]=>
int(27573)
}
[1]=>
array(2) {
["id"]=>
int(2)
["distance"]=>
int(93357)
}
[2]=>
array(2) {
["id"]=>
int(3)
["distance"]=>
int(84515)
}
[3]=>
array(2) {
["id"]=>
int(4)
["distance"]=>
int(13666)
}
[4]=>
array(2) {
["id"]=>
int(5)
["distance"]=>
int(11810)
}
[5]=>
array(2) {
["id"]=>
int(6)
["distance"]=>
int(37548)
}
[6]=>
array(2) {
["id"]=>
int(7)
["distance"]=>
int(10705)
}
[7]=>
array(2) {
["id"]=>
int(8)
["distance"]=>
int(73548)
}
}
--sorted data--
array(8) {
[0]=>
array(2) {
["id"]=>
int(7)
["distance"]=>
int(10705)
}
[1]=>
array(2) {
["id"]=>
int(5)
["distance"]=>
int(11810)
}
[2]=>
array(2) {
["id"]=>
int(4)
["distance"]=>
int(13666)
}
[3]=>
array(2) {
["id"]=>
int(1)
["distance"]=>
int(27573)
}
[4]=>
array(2) {
["id"]=>
int(6)
["distance"]=>
int(37548)
}
[5]=>
array(2) {
["id"]=>
int(8)
["distance"]=>
int(73548)
}
[6]=>
array(2) {
["id"]=>
int(3)
["distance"]=>
int(84515)
}
[7]=>
array(2) {
["id"]=>
int(2)
["distance"]=>
int(93357)
}
}
--grab first result ( lowest )--
array(2) {
["id"]=>
int(7)
["distance"]=>
int(10705)
}
短版
function distanceSorter($a, $b) {
return $a['distance'] - $b['distance'];
}
usort($data, 'distanceSorter');
// if you really just want the lowest value
$lowestDistance = array_shift(usort($data, 'distanceSorter');