Php 按ID更新数组
我有以下数组Php 按ID更新数组,php,Php,我有以下数组 $arrays = array( array( 'id' => 1, 'name' => '', 'cat_name' => 'Food & Beverage', 'quantity' => 1, 'price' => 25, 'image' => 'books_image/calories_fat_carbohydrate.png' ), array( 'id' => 2,
$arrays = array(
array( 'id' => 1, 'name' => '', 'cat_name' => 'Food & Beverage', 'quantity' => 1,
'price' => 25, 'image' => 'books_image/calories_fat_carbohydrate.png' ),
array( 'id' => 2, 'name' => '', 'cat_name' => 'Food & Beverage', 'quantity' => 5,
'price' => 38, 'image' => 'books_image/the_law_relating_to_food.png' ),
array( 'id' => 3, 'name' => '', 'cat_name' => 'Food & Beverage', 'quantity' => 5,
'price' => 19, 'image' => 'books_image/it_starts_with_food.png' ),
array( 'id' => 1, 'name' => '', 'cat_name' => 'Food & Beverage', 'quantity' => 2,
'price' => 19, 'image' => 'books_image/it_starts_with_food.png' )
);
我想要的结果是:
$arrays = array(
array( 'id' => 1, 'name' => '', 'cat_name' => 'Food & Beverage', 'quantity' => 3,
'price' => 25, 'image' => 'books_image/calories_fat_carbohydrate.png' ),
array( 'id' => 2, 'name' => '', 'cat_name' => 'Food & Beverage', 'quantity' => 5,
'price' => 38, 'image' => 'books_image/the_law_relating_to_food.png' ),
array( 'id' => 3, 'name' => '', 'cat_name' => 'Food & Beverage', 'quantity' => 5,
'price' => 19, 'image' => 'books_image/it_starts_with_food.png' ),
);
基本上,当我找到具有相同密钥ID的数组时,我希望将它们添加到数量中。
如何在php中轻松实现这一点?我一直绊倒在这个问题上,并尝试了以下方法,但它根本不起作用
for ($i=0; $i<count($arrays); $i++) {
// if this is not the first loop and if this is a duplicate
if(isset($temp_id) && $temp_id == $arrays[$i]['id']) {
// add quantity of the previous array here
$arrays[$i]['quantity'] += $temp_quantity;
// unset previous array
unset($arrays[$i-1]);
}
$temp_id = $arrays[$i]['id'];
$temp_quantity = $arrays[$i]['quantity'];
}
可用于此:
$result = array_values(array_reduce($arrays, function ($result, $entry) {
if (isset($result[$entry['id']])) {
$result[$entry['id']]['quantity'] += $entry['quantity'];
}
else {
$result[$entry['id']] = $entry;
}
return $result;
}, []));
其他字段是不相关的。