为了账号安全,请及时绑定邮箱和手机立即绑定

如何根据 PHP 中的最高数量从多个数组中找到数组?

如何根据 PHP 中的最高数量从多个数组中找到数组?

PHP
翻翻过去那场雪 2022-10-28 15:21:42
我在多个数组中遇到一些问题来查找高度量数组。我想在 PHP 中将具有大量数组的数组从多个数组转换为一个新数组。如果两个或多个数组的最高数量相同,则将任何数组作为新数组。目前,我有两个具有相同数量但不是最高值的数组,因此它不会在示例数据中选择。输出数组应与最高数量及其代码和类型相结合。输入:(    [0] => Array        (            [code] => Custom discount            [amount] => 3514.55            [type] => fixed_amount        )    [1] => Array        (            [code] => MerOrder300            [amount] => 400.00            [type] => fixed_amount        )    [2] => Array        (            [code] => MerOrder400            [amount] => 400.00            [type] => fixed_amount        )    [3] => Array        (            [code] => MerOrder450            [amount] => 450.00            [type] => fixed_amount        ))输出:(     [0] => Array        (            [code] => Custom discount            [amount] => 3514.55            [type] => fixed_amount        ))
查看完整描述

3 回答

?
阿波罗的战车

TA贡献1862条经验 获得超6个赞

您可以array_column使用array_keysmax

$amountArr = array_column($arr, null, 'amount');
print_r($amountArr[max(array_keys($amountArr))]);

工作示例:- https://3v4l.org/d2WRf


查看完整回答
反对 回复 2022-10-28
?
浮云间

TA贡献1829条经验 获得超4个赞

Rakesh 的解决方案通过在调用期间使用amount作为新键消除了多个限定子数组的可能性。array_column()

至少有几种不同的方法可以执行此任务。这只是一个 - 提取最大值,然后使用该值过滤整个数组。

代码:(演示

$array = [

    [

        'code' => 'Custom discount',

        'amount' => 3514.55,

        'type' => 'fixed_amount'

    ],

    [

        'code' => 'MerOrder300',

        'amount' => 400.00,

        'type' => 'fixed_amount'

    ],

    [

        'code' => 'MerOrder400',

        'amount' => 3514.55,

        'type' => 'fixed_amount'

    ],

    [

        'code' => 'MerOrder450',

        'amount' => 450.00,

        'type' => 'fixed_amount'

    ]

];


$max = max(

    array_column($array, 'amount')

);

var_export(

    array_filter(

        $array,

        function($subarray) use ($max) {

            return $subarray['amount'] == $max;

        }

    )

);


查看完整回答
反对 回复 2022-10-28
?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

您可以使用foreach:


$arr = [

    [

        'code' => 'Custom discount', 

        'amount' => 3514.55,

        'type' => 'fixed_amount'

    ],

    [

        'code' => 'MerOrder300', 

        'amount' => 400.00,

        'type' => 'fixed_amount'

    ],    

    [

        'code' => 'MerOrder400', 

        'amount' => 400.00,

        'type' => 'fixed_amount'

    ],

    [

        'code' => 'MerOrder450', 

        'amount' => 450.00,

        'type' => 'fixed_amount'

    ]

];


$max = $arr[0];


foreach ($arr as $line) {

    if ($line['amount'] > $max['amount']) {

        $max = $line;

    }

}


print_r($max);


查看完整回答
反对 回复 2022-10-28
  • 3 回答
  • 0 关注
  • 87 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信