Php 从中的关联数组中获取最大值,如果相等,则使用最小的其他值获取最大值

Php 从中的关联数组中获取最大值,如果相等,则使用最小的其他值获取最大值,php,arrays,Php,Arrays,让我尽量简单地解释一下。我有一个数组,其中包含几个产品的运费 我有 项目ID 本地航运 国际航运 额外的本地航运 额外国际航运 为了方便起见,我只需要知道如何计算本地运输的部分。之后,我可以将相同的公式应用于国际航运部分 阵列可能包含1个、5个或100个产品,每个产品的数量不同(或相同),如下所示: Array ( [0] => Array ( [item_id] => 788 [local_shipping] => 13.00

让我尽量简单地解释一下。我有一个数组,其中包含几个产品的运费

我有

项目ID 本地航运 国际航运 额外的本地航运 额外国际航运

为了方便起见,我只需要知道如何计算本地运输的部分。之后,我可以将相同的公式应用于国际航运部分


阵列可能包含1个、5个或100个产品,每个产品的数量不同(或相同),如下所示:

Array ( 

    [0] => Array ( 
        [item_id] => 788 
        [local_shipping] => 13.00 
        [intl_shipping] => 45.00 
        [addl_local_shipping] => 10.00 
        [addl_intl_shipping] => 20.00 
    )
    [1] => Array ( 
        [item_id] => 234 
        [local_shipping] => 23.00 
        [intl_shipping] => 5.00 
        [addl_local_shipping] => 1.00 
        [addl_intl_shipping] => 2.00 
    )
    [2] => Array ( 
        [item_id] => 543 
        [local_shipping] => 23.00 
        [intl_shipping] => 6.00 
        [addl_local_shipping] => 0.50 
        [addl_intl_shipping] => 5.00 
    )

) 
因此,我试图得到的是包含最高本地_shipping值的数组,在这种情况下,它将是带“23.00”的[1]和[2]

如果只有一个唯一的最高值,我需要它返回“local_shipping”和“addl_local_shipping”,如

现在,如果有两个数组具有共同的最高值,我需要它返回具有最低“addl_local_shipping”值的数组,在这种情况下是[2],类似于:

Local Shipping is 23.00 and additional local shipping is 0.50
这有意义吗

我能够通过以下方法从阵列中获得最高的“本地装运”值:

$max = 0;
foreach( $my_array as $k => $v )
{
$max = max( array( $max, $v['local_shipping'] ) );
}
echo "Local Shipping is " . $max;

但我不知道如何打印相关的“addl_local_shipping”字符串,并在有多个字符串具有相同的高值时解决问题。

您可以使用
usort
根据本地shipping降序和附加升序对数组进行排序,然后从数组中的第一个结果中获取值:

usort($array, function($a, $b){
    return $b['local_shipping'] - $a['local_shipping'] ?:
        $a['addl_local_shipping'] - $b['addl_local_shipping'];
});

echo 'local shipping: ' . $array[0]['local_shipping'];
echo 'additional local shipping: ' . $array[0]['addl_local_shipping'];

但是,如注释中所述,如果您是从sql查询中获取此数据,那么让数据库使用
orderby
子句为您完成工作就更有意义了。结果将是相同的-数组中的第一个元素将包含您需要的数据

“数组可能包含1个、5个或100个产品”-此数组的来源是什么?它来自mySQL查询。但结构将始终保持不变。ID和成本值始终是数字。我们写下了相同的想法,所以只有一个额外的想法:只需使用
ORDER BY local_shipping DESC,addl_local_shipping ASC查询记录,而不是使用usort…@VolkerK哦,是的,我没有看到关于数组源的评论-如果来自sql查询,那么是的,这肯定是最好的方法。威尔写了张便条说真的,我想得太多了。你的答案是正确的。我使用了mySQL,它可以工作:)
usort($array, function($a, $b){
    return $b['local_shipping'] - $a['local_shipping'] ?:
        $a['addl_local_shipping'] - $b['addl_local_shipping'];
});

echo 'local shipping: ' . $array[0]['local_shipping'];
echo 'additional local shipping: ' . $array[0]['addl_local_shipping'];