
本文介绍如何遍历 CodeIgniter 多维购物车数组,按嵌套的 friend_id(排除 0)聚合每位好友的 sum_price 总和,并生成可用于数据库存储的键值映射数组。
本文介绍如何遍历 codeigniter 多维购物车数组,按嵌套的 `friend_id`(排除 `0`)聚合每位好友的 `sum_price` 总和,并生成可用于数据库存储的键值映射数组。
在电商或共享点餐类应用中,常需支持“一人下单、多人分摊”的场景。例如用户为自己及多位朋友下单,每项商品通过 options.friend_id 标明归属人(0 表示下单人自己),而实际结算时需汇总每位朋友所购商品的总金额(即 sum_price 字段),用于后续记账或收款。
由于 friend_id 深度嵌套在每一项商品的 options 子数组中,且不能重构原始数据结构(如将 friend_id 提升至顶层),因此必须采用深度遍历 + 分组累加策略。核心逻辑如下:
- 遍历最内层商品数组(即 $_cart['array']['carthashidX'] 下的每个订单项);
- 跳过 options.friend_id === 0 的条目(代表下单人自身);
- 以 friend_id 为键,初始化或累加其对应的 sum_price;
- 最终输出形如 ['52' => 35, '28' => 5] 的关联数组,可直接用于批量 INSERT ... ON DUPLICATE KEY UPDATE 或 REPLACE INTO。
以下是完整、健壮的实现代码(兼容 PHP 7.1+,已适配真实 CodeIgniter 购物车结构):
// 假设 $cart_data 是从 CodeIgniter 购物车获取的完整数组(含 array、finalSum 等字段)
$friends_owed = [];
// 安全遍历:确保多级键存在
if (isset($cart_data['array']) && is_array($cart_data['array'])) {
foreach ($cart_data['array'] as $cart_hash => $items) {
if (!is_array($items)) continue;
foreach ($items as $item) {
// 检查必要嵌套结构
if (!isset($item['options']['friend_id']) || !isset($item['sum_price'])) {
continue;
}
$friend_id = (int)$item['options']['friend_id'];
$amount = (float)$item['sum_price'];
// 排除本人(friend_id == 0)
if ($friend_id === 0) {
continue;
}
// 初始化并累加
if (!isset($friends_owed[$friend_id])) {
$friends_owed[$friend_id] = 0.0;
}
$friends_owed[$friend_id] += $amount;
}
}
}
// 可选:对结果排序(按 friend_id 升序),便于调试或展示
ksort($friends_owed);
// 输出示例:
// Array (
// [28] => 5
// [52] => 35
// )
print_r($friends_owed);
✅ 注意事项与最佳实践:
- 类型安全:显式转换 friend_id 为 (int)、sum_price 为 (float),避免字符串拼接或非数字累加错误;
- 空值防御:使用 isset() 和 is_array() 提前校验嵌套键,防止 Notice: Undefined index;
- 精度控制:若涉及货币,建议统一使用整数(单位:分)存储与计算,避免浮点误差;
- 扩展性:如需支持多购物车哈希(如 carthashid1, carthashid2),外层 foreach 已天然支持;
- 数据库写入建议:生成 $friends_owed 后,推荐使用 CodeIgniter Query Builder 批量更新:
foreach ($friends_owed as $fid => $amt) {
$this->db->replace('friends_debt', [
'friend_id' => $fid,
'amount' => round($amt, 2),
'updated_at' => date('Y-m-d H:i:s')
]);
}
该方案简洁、高效、无依赖,可直接集成进 CodeIgniter 的控制器或模型中,精准解决“深层嵌套 ID 分组求和”这一典型业务需求。










