获取 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',
),
)
我需要提取最小和最大权重值。 在此示例中
$min_value = 175
$max_value = 200
关于如何执行此操作有任何帮助吗? 谢谢 !
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 !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
选项 1。 首先映射数组以获取这些数字(而不是完整的详细信息):
然后获得最小值和最大值:
选项 2。(仅当您不这样做时)没有 PHP 5.5 或更高版本)与选项 1 相同,但要提取值,请使用
array_map
:选项 3。选项 4。如果您只需要最小值或最大值,
array_reduce()
可能会更快:这会执行更多
min()
,但速度非常快。PHP_INT_MAX
是从高位开始,然后越来越低。您可以对$max
执行相同的操作,但要从0
或-PHP_INT_MAX
开始。Option 1. First you map the array to get those numbers (and not the full details):
Then you get the min and max:
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
:Option 3.Option 4. If you only need a min OR max,
array_reduce()
might be faster:This does more
min()
s, but they're very fast. ThePHP_INT_MAX
is to start with a high, and get lower and lower. You could do the same for$max
, but you'd start at0
, or-PHP_INT_MAX
.对于使用 PHP 5.5+ 的人来说,使用 array_column 可以更轻松地完成此操作。不再需要那些丑陋的 array_maps 了。
如何获取最大值:
如何获取最小值
For the people using PHP 5.5+ this can be done a lot easier with array_column. Not need for those ugly array_maps anymore.
How to get a max value:
How to get the min value
有趣的是,上面的两个解决方案都使用数组形式的额外存储(第一个解决方案使用两个数组,第二个解决方案使用一个数组),然后您使用“额外存储”数组找到最小值和最大值。虽然这在现实编程世界中可能是可以接受的(谁给出了关于“额外”存储的两位数?),但它会让您在编程 101 中获得“C”。
只需额外两个即可轻松解决查找最小值和最大值的问题内存插槽
It is interesting to note that both the solutions above use extra storage in form of arrays (first one two of them and second one uses one array) and then you find min and max using "extra storage" array. While that may be acceptable in real programming world (who gives a two bit about "extra" storage?) it would have got you a "C" in programming 101.
The problem of finding min and max can easily be solved with just two extra memory slots
不使用
min
或max
等预定义函数怎么样?How about without using predefined functions like
min
ormax
?从数组中快速打印五个最大和最小数字,而不使用php中的排序数组
:-
print fast five maximum and minimum number from array without use of sorting array in php
:-