获取多维数组从元素的最大值? [英] Get the maximum value from an element in a multidimensional array?
问题描述
我想选择多维数组中特定的键的最大值。我无法进入问题的关键...
因此,阵列(这是比我在这里发帖更长时间)
[0] => stdClass的对象
(
[ID] => 70
[自定义] => 4
[dnum] => 1
[上] =>排列
(
[0] => 66
) )
[1] => stdClass的对象
(
[ID] => 43
[自定义] => 42
[dnum] => 2
[上] =>排列
(
[0] => 77
) )
[2] => stdClass的对象
(
[ID] => 12
[自定义] => 3
[dnum] => 0
[上] =>排列
(
[0] => 99
) )
我试图找到整个阵列的最大dnum的价值,所以在这个例子中,$最大= 2。我知道,最大的功能可以让我做这件事,但我不知道如何引用dnum元素没有把整个事情在foreach循环中,如果我这样做,那么最多将不使用的功能,对不对?
所以,我不能确切地做到这一点:
$最大值= MAX($ myArray的[] - > dnum);
有没有为我做到这一点,而无需重新创建整个阵列的方式?
$最大= 0;
的foreach($数组与obj $)
{
如果($ obj-> dnum> $最大值)
{
$最大= $ obj-> dnum;
}
}
如果你的最高数字是负数,这函数将正常工作。
由于您使用的是一个对象,它可以有自定义属性/结构,我不相信有一个你可以用它来得到它真正的'predefined功能。还不如干脆使用foreach循环。
您真的不能从一个foreach循环了,因为即使是内部功能使用foreach循环,它只是在幕后。
另一个解决方案是
$号=阵列();
的foreach($数组与obj $)
{
$编号[] = $ obj-> dnum;
}
$最大值= MAX($数);
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?
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;
}
}
That function would work correctly if your highest number is negative.
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.
You really can't get away from a foreach loop, as even internal functions use a foreach loop, it is just behind the scenes.
Another solution is
$numbers = array();
foreach($array as $obj)
{
$numbers[] = $obj->dnum;
}
$max = max($numbers);
这篇关于获取多维数组从元素的最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!