让我试着尽可能简单地解释一下。我有一个数组,其中包含几种产品的运费。
我有
商品编号本地运输国际航运额外的本地运输额外的国际运输
为了方便起见,我只需要知道如何计算本地运输的部分。之后,我可以将相同的公式应用于国际运输部分。
该数组可能包含 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
)
)
因此,我试图得到的是包含最高local_shipping值的数组,在这种情况下,该数组将是 [1] 和 [2] 以及"23.00"。
如果只有一个唯一的最大值,我需要它返回"local_shipping"和"addl_local_shipping",例如
Local Shipping is 23.00 and additional local shipping is 1.00
现在,如果有 2 个具有共同最大值的数组,我需要它返回具有最低"addl_local_shipping"值的数组,在这种情况下是 [2],如下所示:
Local Shipping is 23.00 and additional local shipping is 0.50
这有意义吗?
我能够通过以下方式从数组中获取最高的"local_shipping"值:
$max = 0;
foreach( $my_array as $k => $v )
{
$max = max( array( $max, $v['local_shipping'] ) );
}
echo "Local Shipping is " . $max;
但是我不知道如何弄清楚如何打印相关的"addl_local_shipping"字符串,如果有多个具有相同高值的字符串,则如何解决问题。
您可以使用usort
根据本地运输降序和附加升序对数组进行排序,然后从数组中的第一个结果中获取值:
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 查询获取此数据,则让数据库使用 ORDER BY
子句为您完成工作更有意义。结果将是相同的 - 数组中的第一个元素将具有您需要的数据