我在使用数组进行基本数学运算时遇到问题;我有的数组格式是:
Array
(
[id] => 325
[type] =>
[p_type] =>
[fees] =>
[sku] => 412
[amountt] =>
)
Array
(
[id] => 325
[type] =>
[p_type] => Initial
[fees] =>
[sku] => 412
[amount] => 2.22)
Array
(
[id] => 325
[type] =>
[p_type] => Shipping
[fees] =>
[sku] => 412
[amount] =>0.22
)
Array
(
[id] => 325
[type] => shipping_add
[p_type] =>
[fees] =>
[sku] => 412
[amount] => 0.50 )
Array
(
[id] => 325
[type] => comms
[p_type] =>
[fees] => 1.00
[sku] => 412
[amount] => 1.22
)
正如您所看到的,ID是相同的,因此我想循环使用相同ID的每个项目,以计算[amount] + [fees]
的总和,并能够在以后显示它。 / p>
我试图通过另一个数组做一个基本的计算方法:
$data = array($total, $fees, $comms);
$data = array("a" => $total, "b" => $fees, "c" => $comms);
$data = array_sum($data);
然而,这并没有真正给我正确的方法。
答案 0 :(得分:0)
$result = array();
foreach ($myArray as $key=>$value){
if (!isset($result[$myArray[$key]['id']]['amount'])) $result[$myArray[$key]['id']]['amount'] = 0;
if (!isset($result[$myArray[$key]['id']]['fees'])) $result[$myArray[$key]['id']]['fees'] = 0;
$result[$myArray[$key]['id']]['amount'] += $myArray[$key]['amount'];
$result[$myArray[$key]['id']]['fees'] += $myArray[$key]['fees'];
}
echo "<pre>";
print_r($result);
echo "</pre>";