在二维数组中查找最小值/最大值 [英] 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()
所需要,或使用 PHP实现array_column().
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()
也可能不错.
这篇关于在二维数组中查找最小值/最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!