-1

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.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • [Find min/max in a two dimensional array](https://stackoverflow.com/a/28372290/2943403) shows how to access the whole row with functional style syntax. – mickmackusa Jan 25 '23 at 06:54
  • [How to find the largest array from a multi dimensional array](https://stackoverflow.com/a/9749944/2943403) also demonstrates how to return the row with the largest column value. – mickmackusa Jan 25 '23 at 08:01

2 Answers2

2
$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'];
Moishy
  • 3,560
  • 3
  • 23
  • 42
0

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',
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136