Home > OS >  Find row data with the max value for a specific column in a 2d array
Find row data with the max value for a specific column in a 2d array

Time:01-25

I want to find the time and temp in the row with maximum temp value in a 2d array.

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.

CodePudding user response:

$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'];

CodePudding user response:

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',
)
  • Related