How to Determine Minimum and Maximum Values in a Multidimensional PHP Array
In PHP, extracting minimal and maximal values from an array is a straightforward task. To illustrate this, consider the following example:
<code class="php">array (0 => array ( 'id' => '20110209172713', 'Date' => '2011-02-09', 'Weight' => '200', ), 1 => array ( 'id' => '20110209172747', 'Date' => '2011-02-09', 'Weight' => '180', ), 2 => array ( 'id' => '20110209172827', 'Date' => '2011-02-09', 'Weight' => '175', ), 3 => array ( 'id' => '20110211204433', 'Date' => '2011-02-11', 'Weight' => '195', ), )</code>
Option 1: Using Array Functions
Utilize the array_column() function to extract the 'Weight' values:
<code class="php">$weights = array_column($array, 'Weight');</code>
Subsequently, determine the minimum and maximum values:
<code class="php">$minValue = min($weights); $maxValue = max($weights);</code>
Option 2: Using Array and Map Functions (PHP 5.5 or higher)
аналогичный Option 1, но использует array_map() для извлечения значений:
<code class="php">$weights = array_map(function($row) { return $row['Weight']; }, $array); $minValue = min($weights); $maxValue = max($weights);</code>
Option 4: Using Array Reduce for Minimum or Maximum Calculations
For efficiency, use array_reduce() if only minimal or maximal value is required:
<code class="php">$minValue = array_reduce($array, function($minimum, $current) { return min($minimum, $current['Weight']); }, PHP_INT_MAX);</code>
The array_reduce() performs fewer min() operations, making it potentially faster. PHP_INT_MAX represents the initial high value to start the reduction.
The above is the detailed content of How to Find the Minimum and Maximum Values in a Multidimensional PHP Array?. For more information, please follow other related articles on the PHP Chinese website!