获取数组列中的最小值和最大值 [英] Get the minimum and maximum values in an array column

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

问题描述

我有一个这种格式的数组:

I have an array in this format:

$array = [
    ['id' => 117, 'name' => 'Networking', 'count' => 16],
    ['id' => 188, 'name' => 'FTP', 'count' => 23],
    ['id' => 189, 'name' => 'Internet', 'count' => 48],
];

是否有一种好的方法来检索计数"列的最小值和最大值(分别为 16 48 )?

Is there a good way to retrieve the minimum and maximum values of the 'count' column (16 and 48 respectively)?

我可以使用几个循环来执行此操作,但是我想知道是否有更好的方法.

I could do this using a few loops, but I wonder if there may be a better way.

推荐答案

与其他人发布的内容相比,您不能使用

In contrast to what others have posted, you cannot use the min()/max() functions for this problem as these functions do not understand the datastructure (array) which are passed in. These functions only work for scalar array elements.

开始编辑

使用 min()的原因 max() 似乎产生了正确的答案,这与将类型类型转换为整数的数组有关,这是一个

The reason why the use of min() and max() seem to yield the correct answer is related to type-casting arrays to integers which is an undefined behaviour:

转换为整数的行为对于其他类型未定义.不要依靠任何观察到的行为,因为它可以更改,恕不另行通知.

我上面关于类型转换的陈述是错误的.实际上 min() max() 可以处理数组,但不能处理数组OP需要他们工作的方式.使用 min() 和<一个href ="http://de3.php.net/manual/zh/function.max.php" rel ="nofollow noreferrer"> max() 带有多个数组或一个数组元素的数组从左到右逐个元素进行比较:

My statement above about the type-casting was wrong. Actually min() and max() do work with arrays but not in the way the OP needs them to work. When using min() and max() with multiple arrays or an array of arrays elements are compared element by element from left to right:

$val = min(array(2, 4, 8), array(2, 5, 1)); // array(2, 4, 8)
/*
 * first element compared to first element: 2 == 2
 * second element compared to second element: 4 < 5
 * first array is considered the min and is returned
 */

翻译成OP的问题,这表明了为什么直接使用 min() max() 似乎产生了正确的结果.数组的第一个元素是 id 值,因此 min() max() 首先将它们进行比较,因为正确的 id 是最小的 count ,而偶然的结果是正确的 id 最高的是 count 最高的一个.

Translated into the OP's problem this shows the reason why the direct use of min() and max() seems to yield the correct result. The arrays' first elements are the id-values, therefore min() and max() will compare them first, incidentally resulting in the correct result because the lowest id is the one with the lowest count and the highest id is the one with the highest count.

END EDIT

正确的方法是使用循环.

The correct way would be to use a loop.

$a = array(
        array('id' => 117, 'name' => 'Networking', 'count' => 16),
        array('id' => 188, 'name' => 'FTP', 'count' => 23),
        array('id' => 189, 'name' => 'Internet', 'count' => 48)
);
$min = PHP_INT_MAX;
$max = 0;
foreach ($a as $i) {
    $min = min($min, $i['count']);
    $max = max($max, $i['count']);
}

这篇关于获取数组列中的最小值和最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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