38

The Problem

I have a multidimensional array similar to the one below. What I'm trying to achieve is a way to find and retrieve from the array the one with the highest "Total" value, now I know there's a function called max but that doesn't work with a multidimensional array like this.

What I've thought about doing is creating a foreach loop and building a new array with only the totals, then using max to find the max value, which would work, the only issue would then be retrieving the rest of the data which relates to that max value. I'm not sure that's the most efficient way either.

Any ideas?

Array
(
    [0] => Array
        (
            [Key1] => Key1
            [Total] => 13
        )

    [1] => Array
        (
            [Key2] => Key2
            [Total] => 117
        )

    [2] => Array
        (
            [Key3] => Key3
            [Total] => 39
        )
)
4

9 に答える 9

30

simple loop値を比較するか、使用するだけですarray_reduce

$data = array_reduce($data, function ($a, $b) {
    return @$a['Total'] > $b['Total'] ? $a : $b ;
});

print_r($data);

ライブデモを見る

于 2013-06-27T09:30:26.397 に答える
11

It's so basic algorithm.

$max = -9999999; //will hold max val
$found_item = null; //will hold item with max val;

foreach($arr as $k=>$v)
{
    if($v['Total']>$max)
    {
       $max = $v['Total'];
       $found_item = $v;
    }
}

echo "max value is $max";
print_r($found_item);

Working demo

于 2013-06-27T09:40:41.387 に答える
9

この質問が古いことは知っていますが、重複としてマークされた後にここで指摘された別の質問に応えて、次の回答を提供しています。これは、現在の回答で言及されていない別の代替手段です。

max という関数があることは知っていますが、このような多次元配列では機能しません。

array_column最大値を非常に簡単に取得できるようにすることで、それを回避できます。

$arr = [['message_id' => 1,
             'points' => 3],
        ['message_id' => 2,
             'points' => 2],
        ['message_id' => 3,
             'points' => 2]];

// max value
$max = max(array_column($arr, 'points'));

連想キーの取得は、実際には複数のキーが必要になる可能性があることを考えると (複数の$max値に一致する場合)、もう少しトリッキーになります。内の無名関数でこれを行うことができ、値を削除するためにarray_map使用できます。array_filternull

// keys of max value
$keys = array_filter(array_map(function ($arr) use ($max) {
    return $arr['points'] == $max ? $arr['message_id'] : null;
}, $arr));

出力:

array(1) {
  [0]=>
  int(1)
}

複数のキーになってしまい、見つかった最初の一致のみに関心がある場合は、単に を参照してください$keys[0]

于 2016-12-27T15:55:21.733 に答える
3

another simple method will be

$max  = array_map( function( $arr ) {
  global $last;
  return (int)( ( $arr["Total"] > $last ) ? $arr["Total"] : $last );
}, $array );

print_r( max( $max ) );
于 2013-06-27T11:16:46.440 に答える
2
<?php
$myarray = array(
    0 => array(
        'Key1' => 'Key1',
        'Total' => 13,
    ),
    1 => array(
        'Key2' => 'Key2',
        'Total' => 117,
    ),
    2 => array(
        'Key2' => 'Key3',
        'Total' => 39,
    ),
);

$out = array();
foreach ($myarray as $item) {
    $out[] = $item['Total'];
}

echo max($out); //117

unset($out, $item);
于 2017-11-12T10:40:52.787 に答える