获取 PHP 数组中的最小值和最大值 [英] Get min and max value in PHP Array
问题描述
我有一个这样的数组:
<前><代码>数组 (0 =>大批 ('id' => '20110209172713','日期' => '2011-02-09','重量' => '200',),1 =>大批 ('id' => '20110209172747','日期' => '2011-02-09','重量' => '180',),2 =>大批 ('id' => '20110209172827','日期' => '2011-02-09','重量' => '175',),3 =>大批 ('id' => '20110211204433','日期' => '2011-02-11','重量' => '195',),)我需要提取最小和最大权重值.在这个例子中
$min_value = 175
$max_value = 200
有关如何执行此操作的任何帮助?谢谢!
选项 1. 首先映射数组以获取这些数字(而不是完整的详细信息):
$numbers = array_column($array, 'weight')
然后你得到最小值和最大值:
$min = min($numbers);$max = max($numbers);
选项 2.(仅当您没有 PHP 5.5 或更高版本时)与选项 1 相同,但要提取值,请使用 array_map
:>
$numbers = array_map(function($details) {返回 $details['Weight'];}, $array);
选项 3.
选项 4.如果您只需要最小值或最大值,array_reduce()
可能会更快:
$min = array_reduce($array, function($min, $details) {return min($min, $details['weight']);}, PHP_INT_MAX);
这会执行更多 min()
,但它们非常快.PHP_INT_MAX
就是从高开始,然后越来越低.你可以对 $max
做同样的事情,但你会从 0
或 -PHP_INT_MAX
开始.
I have an array like this:
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',
),
)
I need to extract minimal and maximal Weight values. In this example
$min_value = 175
$max_value = 200
Any help on how to do this ? Thank you !
Option 1. First you map the array to get those numbers (and not the full details):
$numbers = array_column($array, 'weight')
Then you get the min and max:
$min = min($numbers);
$max = max($numbers);
Option 2. (Only if you don't have PHP 5.5 or better) The same as option 1, but to pluck the values, use array_map
:
$numbers = array_map(function($details) {
return $details['Weight'];
}, $array);
Option 3.
Option 4. If you only need a min OR max, array_reduce()
might be faster:
$min = array_reduce($array, function($min, $details) {
return min($min, $details['weight']);
}, PHP_INT_MAX);
This does more min()
s, but they're very fast. The PHP_INT_MAX
is to start with a high, and get lower and lower. You could do the same for $max
, but you'd start at 0
, or -PHP_INT_MAX
.
这篇关于获取 PHP 数组中的最小值和最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!