0
如何求和數組的相同值?數組求和元素的相同值?
$arr = [
['id' => 1, 'qty' => 100, 'name' => 'a'],
['id' => 1, 'qty' => 100, 'name' => 'a'],
['id' => 2, 'qty' => 100, 'name' => 'b']
];
成爲:
$arr = [
['id' => 1, 'qty' => 200, 'name' => 'a'],
['id' => 2, 'qty' => 100, 'name' => 'b']
];
我一直在嘗試,但返回
[ 1=>['qty'=>200], 2=>['qty'=>100] ]
我一直在嘗試,但返回
for($i=0; $i<count($cok);$i++){
$item_id = $cok[$i]['id'];
$quantity = $cok[$i]['quantity'];
if (isset($new_items[$item_id])) {
$new_items[$item_id] = ['quantity' => $new_items[$item_id]['quantity'] + $quantity];
} else {
$new_items[$item_id] = ['quantity' => $quantity];
}
}
您是否嘗試過的東西? – Rizier123
foreach()循環+基礎數學 –
您可以使用存儲唯一鍵的映射 – Atri