猿问

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

我正在位置之间进行一些计算,当使用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 -> 132,Boston -> 204并且Miami -> 393,我需要它返回最低的为:


New York -> 132


喵喵时光机
浏览 204回答 3
3回答

萧十郎

您可以使用array_search和min函数来获取该元素的最小值和键$arr = [];foreach($array as $x=>$x_value){&nbsp; $arr[$x]= calculateDistance($start_location, $x_value);}echo 'Key :- '.array_search(min($arr),$arr);echo '<br/>';echo 'Value :-' .min($arr);输出Key :- New YorkValue :- 132

缥缈止盈

您可以定义一个较高的值,然后在循环中进行比较(如果当前值较低),则将其替换(如果不继续)。$start_location = '34.048516, -118.260529';$array = [&nbsp; &nbsp; 'New York' => '40.667646, -73.981803',&nbsp; &nbsp; 'Boston' => '42.356909, -71.072573',&nbsp; &nbsp; 'Miami' => '25.764618, -80.213501',];$lowest_x = 1000.0;$lowest_y = 1000.0;foreach ($array as $key => $value) {&nbsp; &nbsp; if (preg_replace('/([0-9\.]+),(.+)/s', '$1', $value) < $lowest_x) {&nbsp; &nbsp; &nbsp; &nbsp; $lowest_x = (float) trim(preg_replace('/([0-9\.]+),(.+)/s', '$1', $value));&nbsp; &nbsp; }&nbsp; &nbsp; if (preg_replace('/(.+),\s([0-9\.]+)/s', '$2', $value) < $lowest_y) {&nbsp; &nbsp; &nbsp; &nbsp; $lowest_y = (float) trim(preg_replace('/([0-9\.]+),(.+)/s', '$2', $value));&nbsp; &nbsp; }}var_dump($lowest_x);var_dump($lowest_y);我不确定,您想降低哪个值。您可以使用正则表达式来完成。
随时随地看视频慕课网APP
我要回答