在二维数组中查找最小值/最大值 [英] Find min/max in a two dimensional array
问题描述
我有一个具有以下格式的数组:
I have an array with the following format:
Array
(
[0] => Array
(
[DateTime] => "2013-05-22 14:21:01"
[Price] => 102.01
)
[1] => Array
(
[DateTime] => "2013-05-23 15:55:01"
[Price] => 52.60
)
[2] => Array
(
[DateTime] => "2013-05-25 14:23:01"
[Price] => 452.25
)
... etc
)
我需要找出Price
的最低和最高值.
I need to discover the lowest and highest value of Price
.
min
只返回它们的键.我也试过 max(array_map("max", $data))
但它只返回 452.25
.
min
only returns they key. I've also tried max(array_map("max", $data))
but that only returns 452.25
.
我是否必须使用 foreach
并手动完成?
Will I have to use a foreach
and do it manually?
推荐答案
这是获取最小值和最大值的一种方法:
Here's one way to get the min and max values:
$min = min(array_column($array, 'Price'));
$max = max(array_column($array, 'Price'));
返回最小值和最大值的嵌套数组:
To return the nested array for the min and max:
$prices = array_column($array, 'Price');
$min_array = $array[array_search(min($prices), $prices)];
$max_array = $array[array_search(max($prices), $prices)];
你可以在一行中完成每一个,因为这看起来像你想要做的:
You could do each in one line since that looked like what you were trying to do:
$min_array = $array[array_search(min($prices = array_column($array, 'Price')), $prices)];
$max_array = $array[array_search(max($prices = array_column($array, 'Price')), $prices)];
PHP >= 5.5.0 需要 array_column()
或使用 array_column() 的 PHP 实现.
PHP >= 5.5.0 needed for array_column()
or use the PHP Implementation of array_column().
使用 array_map()
来获取最小值和最大值:
Using array_map()
to get just the min and max:
$min = min(array_map(function($a) { return $a['Price']; }, $array));
$max = max(array_map(function($a) { return $a['Price']; }, $array));
可能还有一个很好的 array_filter()
或 array_reduce()
.
There's probably a good array_filter()
or array_reduce()
as well.
这篇关于在二维数组中查找最小值/最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!