简体   繁体   English

在二维数组中查找具有特定列最大值的行数据

[英]Find row data with the max value for a specific column in a 2d array

I want to find the time and temp in the row with maximum temp value in a 2d array.我想在二维数组中具有最大temp值的行中找到timetemp

Here is sample data for my weather array:这是我的天气数组的示例数据:

[
    ['time' => '00:00', 'temp' => '15.1'],
    ['time' => '00:00', 'temp' => '15.1'],
    ['time' => '00:01', 'temp' => '15.1'],
    ['time' => '00:02', 'temp' => '15.1'],
    ['time' => '00:02', 'temp' => '15.1'],
    ['time' => '00:02', 'temp' => '15.0'],
    ['time' => '00:03', 'temp' => '15.0'],
]

I've tried a few google searches and it finds the max temp, but I cannot work out how to get the time associated with that.我尝试了一些谷歌搜索,它找到了最高温度,但我不知道如何获得与之相关的时间。

This is also using WordPress, so I am trying to reduce the WP_Queries I have setup currently.这也使用 WordPress,所以我正在尝试减少我当前设置的 WP_Queries。

$weather = array(
    0 => array( 
        'time' =>'00:00', 
        'temp' => '15.1' 
    ),
    1 => array (
      'time' =>  '00:00',
      'temp' =>  '15.1' 
    ),
    2 => array (
      'time' =>  '00:01', 
      'temp' =>  '15.1' 
    ),
    3 =>  array (
      'time' =>  '00:02', 
      'temp' =>  '15.1' 
    ),
    4 => array (
      'time' =>  '00:02', 
      'temp' =>  '15.1' 
    ),
    5 =>  array (
      'time' =>  '00:02',
      'temp' =>  '15.0' 
    ),
    6 => array (
      'time' =>  '00:03', 
      'temp' =>  '15.0' 
    )
);

$highest_temp = -9999999; //use to set the highest value
$highest_temp_array = null; //use to hold the array

foreach( $weather as $key => $value )
{
    if( $value['temp'] > $highest_temp){
       $highest_temp = $value['temp'];
       $highest_temp_array = $value;
    }
}

echo "highest temp is $highest_temp at time " . $highest_temp_array['time'];

Declare a result array and while iterating, only update the result array if the result array is empty or if the new temp value is greater than the stored temp value.声明一个结果数组并在迭代时,仅当结果数组为空或新的临时值大于存储的临时值时才更新结果数组。

Code: ( Demo )代码:(演示

$result = [];
foreach ($weather as $row) {
    if (!$result || $row['temp'] > $result['temp']) {
        $result = $row;
    }
}

var_export($result);

The result will be the first occurring row with the max temperature.结果将是具有最高温度的第一个出现的行。

array (
  'time' => '00:00',
  'temp' => '15.1',
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM