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

时间:2022-10-28 16:11:01

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元素而不把整个东西放到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?

有没有一种方法可以让我不需要重新创建整个数组?

4 个解决方案

#1


10  

$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);

#2


21  

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));

#3


4  

The simplest way is probably your initial thought, which is to loop your array once, and pull out all the dnum keys 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 dnum properties. 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属性的自定义排序函数对数组进行排序。这可能比仅仅循环数组要慢得多,所以我不建议这样做,除非你需要将数组排序作为副作用。

#4


3  

If you like oneliners

如果你喜欢oneliners

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

#1


10  

$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);

#2


21  

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));

#3


4  

The simplest way is probably your initial thought, which is to loop your array once, and pull out all the dnum keys 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 dnum properties. 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属性的自定义排序函数对数组进行排序。这可能比仅仅循环数组要慢得多,所以我不建议这样做,除非你需要将数组排序作为副作用。

#4


3  

If you like oneliners

如果你喜欢oneliners

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