在二维数组中查找最小值/最大值 [英] Find min/max in a two dimensional array

查看:41
本文介绍了在二维数组中查找最小值/最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下格式的数组:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆