php 从多维数组中的元素中获取最大值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2189479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:25:22  来源:igfitidea点击:

Get the maximum value from an element in a multidimensional array?

phparraysmaxmultidimensional-array

提问by phpN00b

I'm trying to select the maximum value for a particular key in a multidimensional array. I'm having trouble "getting to" the key in question...

我正在尝试为多维数组中的特定键选择最大值。我在“找到”有问题的关键时遇到了麻烦......

So, the array (which is much more lengthy than what I'm posting here)

所以,数组(比我在这里发布的要长得多)

[0] => stdClass Object
    (
        [id] => 70
        [cust] => 4
        [dnum] => 1
        [upper] => Array
            (
                [0] => 66
            )

    )
[1] => stdClass Object
    (
        [id] => 43
        [cust] => 42
        [dnum] => 2
        [upper] => Array
            (
                [0] => 77
            )

    )
[2] => stdClass Object
    (
        [id] => 12
        [cust] => 3
        [dnum] => 0
        [upper] => Array
            (
                [0] => 99
            )

    )

I'm trying to find the maximum "dnum" value across the entire array, so in this example, $max = 2. I know that the max function allows me to do this, but I'm not sure how to reference the dnum element without putting the whole thing in a foreach loop, and if I do that, then max wouldn't be the function to use, right?

我试图在整个数组中找到最大的“dnum”值,所以在这个例子中,$max = 2。我知道 max 函数允许我这样做,但我不确定如何引用 dnum element 没有将整个事情放在 foreach 循环中,如果我这样做,那么 max 将不是要使用的函数,对吗?

So, I can't exactly do this:

所以,我不能完全做到这一点:

$max = max($myarray[]->dnum);

Is there a way for me to do this without having to recreate the entire array?

有没有办法让我不必重新创建整个数组?

采纳答案by Tyler Carter

$max = 0;
foreach($array as $obj)
{
    if($obj->dnum > $max)
    {
        $max = $obj->dnum;
    }
}

That function would work correctly if your highest number is not negative (negatives, empty arrays, and 0s will return the max as 0).

如果您的最高数字不是负数(负数、空数组和 0 将最大值返回为 0),则该函数将正常工作。

Because you are using an object, which can have custom properties/structures, I don't believe there are really any 'predefined' functions you can use to get it. Might as well just use a foreach loop.

因为您使用的是可以具有自定义属性/结构的对象,所以我不相信您真的可以使用任何“预定义”函数来获取它。也可以只使用 foreach 循环。

You really can't get away from a foreach loop, as even internal functions use a foreach loop, it is just behind the scenes.

你真的无法摆脱 foreach 循环,因为即使是内部函数也使用 foreach 循环,它只是在幕后。

Another solution is

另一个解决方案是

$numbers = array();
foreach($array as $obj)
{
    $numbers[] = $obj->dnum;
}
$max = max($numbers);

回答by cletus

In PHP 5.2 the only way to do this is to loop through the array.

在 PHP 5.2 中,唯一的方法是遍历数组。

$max = null;
foreach ($arr as $item) {
  $max = $max === null ? $item->dnum : max($max, $item->dnum);
}

Note:I've seeded the result with 0 because if all the dnum values are negative then the now accepted solution will produce an incorrect result. You need to seed the max with something sensible.

注意:我将结果设为 0,因为如果所有 dnum 值都是负数,那么现在接受的解决方案将产生不正确的结果。你需要用一些明智的东西来播种最大值。

Alternatively you could use array_reduce():

或者,您可以使用array_reduce()

$max = array_reduce($arr, 'max_dnum', -9999999);

function max_denum($v, $w) {
  return max($v, $w->dnum);
}

In PHP 5.3+ you can use an anonymous function:

在 PHP 5.3+ 中,您可以使用匿名函数:

$max = array_reduce($arr, function($v, $w) {
  return max($v, $w->dnum);
}, -9999999);

You can use array_map()too:

您也可以使用array_map()

function get_dnum($a) {
  return $a->dnum;
}

$max = max(array_map('get_dnum', $arr));

回答by zombat

The simplest way is probably your initial thought, which is to loop your array once, and pull out all the dnumkeys into a separate array, then call max()on that:

最简单的方法可能是您最初的想法,即循环一次数组,并将所有dnum键拉出到一个单独的数组中,然后调用max()它:

$out = array();
foreach($myarray as $obj) {
    $out[] = $obj->dnum;
}
echo max($out);

You could do it without creating a separate array, but you'll end up calling max()a lot more often. Performance/memory usage will be different between the two, you could always benchmark it:

您可以在不创建单独数组的情况下执行此操作,但最终会max()更频繁地调用。两者之间的性能/内存使用情况会有所不同,您可以随时对其进行基准测试:

$first = $myarray[0];  //assume zero start index
$max = $first->dnum;
foreach($myarray as $obj) {
    $max = max($max,$obj->dnum);
}
echo $max;

The only other way you could go about it would be to sort your array using usort()and a custom sorting function based on the object dnumproperties. This is probably going to be much slower than just looping your array however, so I don't think I'd recommend it unless you needed the array sorted as a side effect.

您可以进行的唯一其他方法是使用usort()基于对象dnum属性的自定义排序函数对数组进行排序。但是,这可能比仅循环数组要慢得多,所以我不认为我会推荐它,除非您需要将数组排序为副作用。

回答by DarkMukke

If you like oneliners

如果你喜欢单线

$max = max( array_map(function( $row ){ return $row->dnum; }, $myarray) );

回答by Danimal Reks

For anyone still interested, try this...

对于任何仍然感兴趣的人,试试这个......

 $min = min(array_column($myarray, 'dnum'));
 $max = max(array_column($myarray, 'dnum'));