Extracting Minimum and Maximum Values from a Multidimensional Array in PHP
Given an array with nested values, obtaining the minimum and maximum values for a specific key can be challenging. Consider the following example:
<code class="php">$array = 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>
To extract the minimum and maximum weights, several solutions exist:
Option 1:
<code class="php">$numbers = array_column($array, 'Weight'); $min_value = min($numbers); $max_value = max($numbers);</code>
Option 2:
<code class="php">$numbers = array_map(function($details) { return $details['Weight']; }, $array); $min_value = min($numbers); $max_value = max($numbers);</code>
Option 4:
<code class="php">$min_value = array_reduce($array, function($min, $details) { return min($min, $details['Weight']); }, PHP_INT_MAX); $max_value = array_reduce($array, function($max, $details) { return max($max, $details['Weight']); }, -PHP_INT_MAX);</code>
By employing these techniques, you can effectively retrieve the minimum and maximum values from a multidimensional array in PHP, helping you analyze and process data effectively.
The above is the detailed content of How to Find the Minimum and Maximum Values in a Multidimensional Array Using PHP?. For more information, please follow other related articles on the PHP Chinese website!