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?
The amax() method is used to find the maximum value across the axis or in a given 1D array. Below is the syntax to use the method: numpy. amax(array, axis);
M = max( A ) returns the maximum elements of an array. If A is a vector, then max(A) returns the maximum of A . If A is a matrix, then max(A) is a row vector containing the maximum value of each column of A .
Multidimensional arrays are an extension of 2-D matrices and use additional subscripts for indexing. A 3-D array, for example, uses three subscripts. The first two are just like a matrix, but the third dimension represents pages or sheets of elements.
$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).
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With