簡體   English   中英

在二維數組中查找具有特定列最大值的行數據

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

我想在二維數組中具有最大temp值的行中找到timetemp

這是我的天氣數組的示例數據:

[
    ['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'],
]

我嘗試了一些谷歌搜索,它找到了最高溫度,但我不知道如何獲得與之相關的時間。

這也使用 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'];

聲明一個結果數組並在迭代時,僅當結果數組為空或新的臨時值大於存儲的臨時值時才更新結果數組。

代碼:(演示

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

var_export($result);

結果將是具有最高溫度的第一個出現的行。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM