获取数组列中的最小值和最大值

发布于 2024-08-03 03:30:30 字数 359 浏览 7 评论 0 原文

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

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

有没有好的方法来检索“计数”列的最小值和最大值(分别为 1648)?

我可以使用几个循环来做到这一点,但我想知道是否有更好的方法。

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],
];

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

坏尐絯 2024-08-10 03:30:30

与其他人发布的内容相反,您不能使用 min()< /code>/max()< /a> 解决此问题的函数,因为这些函数不理解传入的数据结构(数组)。 这些函数仅适用于标量数组元素。


开始编辑

之所以使用min()max() 似乎产生正确的答案与将数组类型转换为整数有关,这是一个 未定义行为

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

我上面关于类型转换的陈述是错误的。实际上 min()max() 可以处理数组,但不能在OP 需要它们工作的方式。当使用 min()max() 具有多个数组或数组数组元素从左到右逐个元素进行比较:

$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 的那个。 code>id 是count 最高的那个。

END EDIT


正确的方法是使用循环。

$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']);
}

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.


BEGIN EDIT

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:

The behaviour of converting to integer
is undefined for other types. Do not
rely on any observed behaviour, as it
can change without notice.

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
 */

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']);
}
我做我的改变 2024-08-10 03:30:30

正如您从前面的答案中看到的,有许多可行的技术需要考虑。

如果您正在考虑最佳性能,那么您应该最小化所使用的循环数量和函数调用数量。

“在幕后”,本机函数 min()max() 将完全迭代它们所输入的数组。因此,如果您使用函数或构造来循环二维输入数组,然后调用 min(),然后调用 max(),您将迭代完整的输入数组长度的三次。

考虑这个仅迭代 1 次的代码片段:

代码:(演示)

$min = array_shift($array)['count'] ?? null;
$max = $min;
foreach ($array as $row) {
    if ($min > $row['count']) {
        $min = $row['count'];
    }
    if ($max < $row['count']) {
        $max = $row['count'];
    }
}
var_export(['min' => $min, 'max' => $max]);
  • 上述优点是
    • 仅 1 次函数调用(提取第一行数据)和一个循环
    • 它不会多次遇到相同的数据
    • 简单的数字比较对于 php 来说执行起来非常简单/快速
  • 上述的缺点是
    • 它通过调用 array_shift() 来改变输入数组,因此,如果您在同一范围内重复使用该数组,它将不再包含第一个值
    • 它比其他一些技术更冗长,并且忽略了一些可行的本机函数

另一种技术重视函数式代码。 PHP 有本机函数可以让这项任务井井有条。

array_column() 可以隔离 count 列中的所有值。
min() 返回最小的数字。
max() 返回最大数字。

代码:(Demo)

$counts = array_column($array, 'count');
var_export(['min' => min($counts), 'max' => max($counts)]);
  • 以上的优点是
    • 只有 1 个临时变量
    • 它不会改变输入数组
    • 非常简洁、直观和声明性的编码风格
    • 如果其中一行缺少 count 元素,它不会生成任何警告
  • 上述缺点是
    • 从技术上讲,它会迭代数据三次
    • 它的性能很可能比第一个片段更差

As you can see from the earlier answers, there are many viable techniques to consider.

If you are considering best performance, then you should be minimizing the number of loops that are used and the number of function calls.

"Under the hood", the native functions min() and max() will be fully iterating the array that they are fed. So, if you use a function or construct to loop over the 2-dimensional input array, then call min(), then call max(), you are iterating the full length of the input array three separate times.

Consider this snippet that only iterates 1 time:

Code: (Demo)

$min = array_shift($array)['count'] ?? null;
$max = $min;
foreach ($array as $row) {
    if ($min > $row['count']) {
        $min = $row['count'];
    }
    if ($max < $row['count']) {
        $max = $row['count'];
    }
}
var_export(['min' => $min, 'max' => $max]);
  • The advantages of above are
    • only 1 function call (to extract the first row's data) and one loop
    • it never encounters the same data more than once
    • simple numeric comparisons are very simple/fast for php to execute
  • The disadvantages of above are
    • it mutates the input array by calling array_shift(), so if you re-use the array in the same scope, it will no longer contain the first value
    • it is more verbose than some other techniques and ignores some viable native functions

Another technique places value on functionally styled code. PHP has native functions that make tidy work of this task.

array_column() can isolate all of the values in the count column.
min() returns the lowest number.
max() returns the highest number.

Code: (Demo)

$counts = array_column($array, 'count');
var_export(['min' => min($counts), 'max' => max($counts)]);
  • The advantages of above are
    • only 1 temporary variable
    • it does not mutate the input array
    • very concise, intuitive, and declarative coding style
    • it will not generate any warnings if one of the rows is missing the count element
  • The disadvantages of above are
    • it technically iterates the data three times
    • it very likely performs worse that the first snippet
梨涡 2024-08-10 03:30:30

您可以使用 max()min() 函数。

You could use the max() and min() functions.

茶底世界 2024-08-10 03:30:30

你用几个循环做了什么?一个就足够了:)

  1. 获取第一个元素,将计数分配给 $min 和 $max
  2. 迭代其余元素,将计数与每个 $min 和 $max 进行比较,如果更小/更大,则分配新的计数值

What did you do with a few loops? One is quite enough :)

  1. Get the first element, assing the count to both $min and $max
  2. iterate over the rest, compare count to each $min and $max, if smaller/larger, assign the new count value
提笔落墨 2024-08-10 03:30:30

看起来你不能在二维数组上使用 max() 。它只返回最大的数组,而不是每个索引的 max() (如一些答案中提到的)。

所以:

$count = array();
foreach($arr as $_arr) {
    $count[] = $_arr['count'];
}
var_dump(max($count), min($count));

Looks like you can't use max() on a 2D array. It just returns the largest array, not the max() of each index (as being mentioned in a few answers).

So:

$count = array();
foreach($arr as $_arr) {
    $count[] = $_arr['count'];
}
var_dump(max($count), min($count));
茶花眉 2024-08-10 03:30:30

如果所需的列位于数组中的第一个,您可以使用以下单行代码:

$max = max(array_map('current', $a));
$min = min(array_map('current', $a));

这将找到 id 的最小值/最大值

If the desired column is first in the array you can use the following one-liners:

$max = max(array_map('current', $a));
$min = min(array_map('current', $a));

This will find the min/max of id

万劫不复 2024-08-10 03:30:30

是否有与该函数等效的内置函数?
(即使没有测试能力)

/**
 * extracts a column from a 2D array, with an optional selection over another column
 *
 * @param $aArray     array to extract from
 * @param $aColName   name of the column to extract, ex. 'O_NAME'
 * @param $aColTest   (optional) name of the column to make the test on, ex. 'O_ID'
 * @param $aTest      (optional) string for the test ex. ">= 10", "=='".$toto."'"
 * @return            1D array with only the extracted column
 * @access public
 */

  function extractColFromArray($aArray, $aColName, $aColTest="", $aTest="") {
  $mRes = array();
  foreach($aArray as $row) {
   if (($aColTest == "") || (eval("return " . $row[$aColTest] . $aTest . ";" )) ) {
    $mRes[] = $row[$aColName];
   }
  }
  return $mRes;
 } // extractColFromArray

Is there an equivalent build-in function to that one?
(even without the test capability)

/**
 * extracts a column from a 2D array, with an optional selection over another column
 *
 * @param $aArray     array to extract from
 * @param $aColName   name of the column to extract, ex. 'O_NAME'
 * @param $aColTest   (optional) name of the column to make the test on, ex. 'O_ID'
 * @param $aTest      (optional) string for the test ex. ">= 10", "=='".$toto."'"
 * @return            1D array with only the extracted column
 * @access public
 */

  function extractColFromArray($aArray, $aColName, $aColTest="", $aTest="") {
  $mRes = array();
  foreach($aArray as $row) {
   if (($aColTest == "") || (eval("return " . $row[$aColTest] . $aTest . ";" )) ) {
    $mRes[] = $row[$aColName];
   }
  }
  return $mRes;
 } // extractColFromArray
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文