从多维数组中的元素中获取最大值? [英] Get the maximum value from an element in a multidimensional array?
问题描述
我正在尝试为多维数组中的特定键选择最大值.我在找到"有问题的关键时遇到了麻烦......
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
)
)
我试图在整个数组中找到最大的dnum"值,所以在这个例子中,$max = 2.我知道 max 函数允许我这样做,但我不知道如何引用 dnum 元素而不将整个内容放在 foreach 循环中,如果我这样做,那么 max 将不是要使用的函数,对吗?
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?
所以,我不能完全做到这一点:
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?
推荐答案
$max = 0;
foreach($array as $obj)
{
if($obj->dnum > $max)
{
$max = $obj->dnum;
}
}
如果您的最高数字不是负数(负数、空数组和 0 将最大值返回为 0),该函数将正常工作.
That function would work correctly if your highest number is not negative (negatives, empty arrays, and 0s will return the max as 0).
因为您使用的是可以具有自定义属性/结构的对象,所以我不相信您真的可以使用任何预定义"函数来获取它.也可以只使用 foreach 循环.
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 循环,因为即使是内部函数也使用 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.
另一个解决方案是
$numbers = array();
foreach($array as $obj)
{
$numbers[] = $obj->dnum;
}
$max = max($numbers);
这篇关于从多维数组中的元素中获取最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!