如何获取多维数组的高值


How to get the hight value for multidimensional array

我有以下多维数组:

array(
    array(
        [id] => 65,
        [user_id] => 1,
        [total] => 1
    ),
    array(
        [id] => 66,
        [user_id] => 3,
        [total] => 2
    ),
    array(
        [id] => 67,
        [user_id] => 5,
        [total] => 4
    ),
)

如何获取总计值最高的数组,并且仍然获得数组的完整键值,如下所示:

array(
    [id] => 67,
    [user_id] => 5,
    [total] => 4
)

试试这个:

$total = array();
foreach ($data as $key => $row) {
    $total[$key]  = $row['total'];
}
// this sorts your $data array by `total` in descending order
// so the max for `total` is the first element
array_multisort($total, SORT_DESC, $data);

现在,使用 $data[0] ;

使用 usort() 对 id 上的数组进行排序:

function cmp($a, $b)
{
    return strcmp($b["id"], $a["id"]);
}
usort($arr, 'cmp'); // $arr is your array

然后第一个数组具有您想要的值。

有关更多信息,请参阅 usort 上的文档:http://php.net/manual/en/function.usort.php

$array = [
    ['id' => 1, 'total' => 1],
    ['id' => 2, 'total' => 4],
    ['id' => 3, 'total' => 5],
];
function cmp($a, $b) {
    return ($a['total'] < $b['total']) ? 1 : -1;
}
usort($array, 'cmp');
print_r($array[0]); // output ['id' => 3, 'total' => 5]
您可以将

array_column()array_search()一起使用:

$totals = array_column( $array, 'total' );
$result = $array[ array_search( max( $totals ), $totals ) ];

array_column()返回一个带有"总计"值的数组。使用它来检索具有最大总值的主数组的键。

但。。。跟随数组呢?

$array = array(
    array(
        'id' => 65,
        'user_id' => 1,
        'total' => 4
    ),
    array(
        'id' => 66,
        'user_id' => 3,
        'total' => 2
    ),
    array(
        'id' => 67,
        'user_id' => 5,
        'total' => 4
    ),
    array(
        'id' => 68,
        'user_id' => 6,
        'total' => 2
    )
);

要过滤所有最大值,您可以使用以下内容:

$max = max( array_column( $array, 'total' ) );
$result = array_filter
(
    $array,
    function( $row ) use ( $max )
    {
        return $row['total'] == $max;
    }
);
print_r( $result );

输出:

Array
(
    [0] => Array
        (
            [id] => 65
            [user_id] => 1
            [total] => 4
        )
    [2] => Array
        (
            [id] => 67
            [user_id] => 5
            [total] => 4
        )
)

输入$max变量最大值"总计"列,然后使用它来过滤原始数组并检索将其作为总计的所有行。


  • 阅读更多 关于 array_column()
  • 阅读更多 关于 array_filter()

你可以安装 xdebug for var_dump并按顺序查看你

var_dump($array);

在你可以通过键获得所需的数组之后

$array[3]; //example for question context

或通过foreach进行分析

$arrayResult = array();
foreach($array as $_arr) {
   if($_arr['user_id'] == 5) {
      $arrayResult = $_arr;
   }
}
var_dump($arrayResult);

这也是您的问题上下文的示例