从foreach循环中获取最低的键和值

时间:2019-05-04 06:08:02

标签: php

我正在位置之间进行一些计算,我需要获取最低键和在foreach完成后返回的值。我该如何实现?

// Los Angeles
$start_location = '34.048516, -118.260529';

$array=array(
'New York'=>'40.667646, -73.981803',
'Boston'=>'42.356909, -71.072573',
'Miami'=>'25.764618, -80.213501'
);


foreach($array as $x=>$x_value){

  echo $x." -> ".calculateDistance($start_location, $x_value);
  // Prints a number like "334".

}

例如,如果New York -> 132Boston -> 204Miami -> 393,我需要它返回最低的一个:

New York -> 132

3 个答案:

答案 0 :(得分:5)

您可以使用array_searchmin函数来获取该元素的最小值和键

$arr = [];
foreach($array as $x=>$x_value){
  $arr[$x]= calculateDistance($start_location, $x_value);
}
echo 'Key :- '.array_search(min($arr),$arr);
echo '<br/>';
echo 'Value :-' .min($arr);

输出

Key :- New York
Value :- 132

答案 1 :(得分:1)

您快到了。只需保留一个$lowest_data$lowest_dist变量。在执行操作时遍历数组。计算距离并相应地更新$lowest_dist$lowest_data变量。

<?php

$start_location = '34.048516, -118.260529';

$array=array(
    'New York'=>'40.667646, -73.981803',
    'Boston'=>'42.356909, -71.072573',
    'Miami'=>'25.764618, -80.213501'
);

$lowest_data = [];
$lowest_dist = -1;

foreach($array as $x=>$x_value){
  $distance = calculateDistance($start_location, $x_value)
  if($lowest_dist === -1 || $lowest_dist > $distance){
    $lowest_dist = $distance;
    $lowest_data = [
        $x => $x_value
    ];
  }
}


echo "Lowest distance ",$lowest_dist,PHP_EOL;
print_r($lowest_data);

答案 2 :(得分:0)

您可以定义一个较高的值,然后在循环中进行比较,如果当前值较低,则将其替换(如果不继续)。

$start_location = '34.048516, -118.260529';

$array = [
    'New York' => '40.667646, -73.981803',
    'Boston' => '42.356909, -71.072573',
    'Miami' => '25.764618, -80.213501',
];

$lowest_x = 1000.0;
$lowest_y = 1000.0;
foreach ($array as $key => $value) {
    if (preg_replace('/([0-9\.]+),(.+)/s', '$1', $value) < $lowest_x) {
        $lowest_x = (float) trim(preg_replace('/([0-9\.]+),(.+)/s', '$1', $value));
    }

    if (preg_replace('/(.+),\s([0-9\.]+)/s', '$2', $value) < $lowest_y) {
        $lowest_y = (float) trim(preg_replace('/([0-9\.]+),(.+)/s', '$2', $value));
    }
}

var_dump($lowest_x);
var_dump($lowest_y);

我不确定,您想降低哪个值。您可以使用正则表达式来做到这一点。