获取存储在多维数组中的重复ID的总和



我在codeigniter中向购物车添加了一个多维项目数组。假设我为我和几个朋友点了食物(特定的ID存储在下一级数组中(。现在,如果有人有更多的项目,我需要获得每个朋友的总金额,并将其保存为我所有的钱。如何循环所有项目以获得每个ID相同的朋友的总总额(我无法将朋友ID移动到父数组(。我以一种我们可以在下表中看到的非重复方式将它们存储到数据库中。我需要一个新的数组来获得这样的结果(存储/更新它们(。

friend_id amount_owned
52 35
28 5
friend_id 0是我…我们跳过我!=0

如果我不必手工编码数组,我会花更少的时间来检查答案,但这里是

$input = [
'array' => [
'carthashid1' => [
[
'foodid' => 322, 'price' => 5,
'name' => 'Chicken Burger', 
'options' => ['friend_id' => 52, 'special_instructions' => ''],
'rowid' => 'ceec8698316fe95ec9d7dccf961f32c1', 'num_added' => 5,'sum_price' => 25
],
[
'foodid' => 322, 'price' => 5,
'name' => 'Beef Burger',
'options' => ['friend_id' => 52,'special_instructions' => ''],
'rowid' => 'ceec8698316fe95ec9d7dccf961f32c1', 'num_added' => 2,'sum_price' => 10
],
[
'foodid' => 322,'price' => 5,'name' => 'Chicken Burger',
'options' => ['friend_id' => 28,'special_instructions' => ''],
'rowid' => 'ceec8698316fe95ec9d7dccf961f32c1', 'num_added' => 1,'sum_price' => 5
],
[
'foodid' => 322, 'price' => 5, 'name' => 'Beef Burger',
'options' => ['friend_id' => 0,'special_instructions' => ''],
'rowid' => 'ceec8698316fe95ec9d7dccf961f32c1', 'num_added' => 1, 'sum_price' => 5
]
]
]
];
$friends = [];
foreach($input['array']['carthashid1']  as $ordered){
if ($ordered['options']['friend_id'] == 0) {
// its me, ignore me
continue;
}
if ( ! isset($friends[$ordered['options']['friend_id']]) ) {
// initialise the accumulator for this friend
$friends[$ordered['options']['friend_id']] = 0; 
} 
$friends[$ordered['options']['friend_id']] += $ordered['sum_price'];    
}
print_r($friends);

结果


Array
(
[52] => 35
[28] => 5
)

理论上,您可以在单个DB查询中完成整个任务,也可以通过修改DB查询将friend_id移动到父数组。

保持friend_id, amount_owned结构的方法略有不同:

$owned = [];
foreach($arr['array']['carthashid1'] as $item){
if(isset($item['options']['friend_id']) && $item['options']['friend_id'] != 0)
{
if(count($owned) && ($key = array_search($item['options']['friend_id'], array_column($owned, 'friend_id'))) !== false){
// we found friend id in array lets add the price:
$owned[$key]['amount_owned'] += $item['sum_price'];
continue;
}
// when we dont find the friend id in array create that item here:
$owned[] = ['friend_id' => $item['options']['friend_id'], 'amount_owned' => $item['sum_price']];
}
}
print_r($owned);

结果:

Array
(
[0] => Array
(
[friend_id] => 52
[amount_owned] => 35
)
[1] => Array
(
[friend_id] => 28
[amount_owned] => 5
)
)

相关内容

最新更新