【问题标题】:How to get max amount of value in same key in array如何在数组中的同一键中获取最大值
【发布时间】:2017-03-23 12:26:57
【问题描述】:

如何获取数组中同一键的最大值

E.x

我有这个数组。

Array
(
    [id] => 1
    [amount] => 4
)
Array
(
    [id] => 1
    [amount] => 3
)
Array
(
    [id] => 2
    [amount] => 3
)

我想要下面的结果。表示我想要相同 id 的最大值。请提供相同的解决方案。

Array
(
    [id] => 1
    [amount] => 4
)
Array
(
    [id] => 2
    [amount] => 3
)

【问题讨论】:

  • 我不认为你可以比 O(n) 更快地做到这一点.....所以只需遍历它们。
  • 是的,先自己尝试一下——这是学习的唯一途径;-)
  • 但我想从数组中删除更少的 id

标签: php arrays sorting multidimensional-array max


【解决方案1】:
<?php
    $bigArray = [
        [
            'id' => 1,
            'amount' => 4
        ],
        [
            'id' => 1,
            'amount' => 3
        ],
        [
            'id' => 2,
            'amount' => 3
        ]
    ];


    $output = [];

    foreach($bigArray as $innerArray){
        if(!isset($output[$innerArray['id']])){
            $output[$innerArray['id']] = $innerArray;
        }
        elseif( $output[$innerArray['id']]['amount'] < $innerArray['amount'] ){
            $output[$innerArray['id']] = $innerArray;
        }
    }

    print_r($output);
    exit;

【讨论】:

    【解决方案2】:

    您可以先使用usort 对数组进行排序,然后再返回第一个结果。例如:

    usort($theBigArray, function($a, $b) {
        return ($a['amount'] - $b['amount']);
    });
    
    print_r($theBigArray);
    

    【讨论】:

    • 它不工作,请提供另一种解决方案
    猜你喜欢
    • 2015-02-15
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-14
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    相关资源
    最近更新 更多