CodeIgniter3民宿预订系统分房型价格计算实现问询
民宿预订系统分房型价格计算实现方案(CodeIgniter3)
一、会话数据解析
先把会话中存储的原始数据拆解为可直接计算的结构化数据:
- 选中房型数组
selectedRoom:直接提取房型标识(如mud_house、standard_ac、luxury_ac)作为遍历基础 - 成人数量数组
adults:按房型_成人数量格式拆分,比如mud_house_2拆分为房型mud_house、成人数量2 - 入住晚数计算:从
dateRange数组(如['2024-05-01', '2024-05-04'])计算,通过时间戳差值获取天数:$nights = (strtotime($dateRange[1]) - strtotime($dateRange[0])) / (3600 * 24); - 儿童年龄组数组
kids_age:按房型_儿童总数_序号_年龄区间格式拆分,比如mud_house_3_1_1-4拆分为房型mud_house、儿童年龄区间1-4,最终整理为每个房型对应的儿童年龄区间列表
二、价格规则配置
将业务规则转化为可维护的数组配置,便于后续调整:
// 成人单价配置:[房型][入住时长区间] => 单价(元/晚/人) $adult_prices = [ 'mud_house' => [ '1' => 180, // 1晚 '2' => 160, // 2晚 '3+' => 140 // 3晚及以上 ], 'standard_ac' => [ '1' => 280, '2' => 250, '3+' => 220 ], 'luxury_ac' => [ '1' => 380, '2' => 340, '3+' => 300 ] ]; // 儿童价格比例配置:[年龄区间] => 成人单价比例(0表示免费) $kid_ratios = [ '1-4' => 0, // 免费 '5-8' => 0.5, // 成人价50% '8-12' => 0.8, // 成人价80% '12+' => 1.0 // 同成人价 ];
三、核心计算逻辑实现
在CodeIgniter3的控制器或模型中编写计算方法:
public function calculate_total_price() { // 1. 从会话获取数据 $selected_rooms = $this->session->userdata('selectedRoom'); $adults_data = $this->session->userdata('adults'); $date_range = $this->session->userdata('dateRange'); $kids_age_data = $this->session->userdata('kids_age'); // 2. 计算入住晚数并校验有效性 $checkin = strtotime($date_range[0]); $checkout = strtotime($date_range[1]); $nights = ($checkout - $checkin) / (3600 * 24); if ($nights <= 0) { return 0; // 无效日期返回0 } // 3. 匹配入住时长对应的单价key $night_key = $nights == 1 ? '1' : ($nights == 2 ? '2' : '3+'); // 4. 解析成人数量为「房型=>数量」的数组 $adult_counts = []; foreach ($adults_data as $item) { list($room_type, $count) = explode('_', $item); $adult_counts[$room_type] = (int)$count; } // 5. 解析儿童年龄区间为「房型=>区间列表」的数组 $kid_age_groups = []; foreach ($kids_age_data as $item) { $parts = explode('_', $item); $room_type = $parts[0]; $age_range = $parts[3]; $kid_age_groups[$room_type][] = $age_range; } // 6. 定义价格配置(可移至config目录下的自定义配置文件) $adult_prices = [ 'mud_house' => ['1' => 180, '2' => 160, '3+' => 140], 'standard_ac' => ['1' => 280, '2' => 250, '3+' => 220], 'luxury_ac' => ['1' => 380, '2' => 340, '3+' => 300] ]; $kid_ratios = ['1-4' => 0, '5-8' => 0.5, '8-12' => 0.8, '12+' => 1.0]; // 7. 遍历房型计算总价 $total_price = 0; foreach ($selected_rooms as $room_type) { // 计算成人总价 $adult_count = isset($adult_counts[$room_type]) ? $adult_counts[$room_type] : 0; $adult_price_per_night = $adult_prices[$room_type][$night_key]; $adult_total = $adult_count * $adult_price_per_night * $nights; // 计算儿童总价 $kid_total = 0; if (isset($kid_age_groups[$room_type])) { foreach ($kid_age_groups[$room_type] as $age_range) { $ratio = $kid_ratios[$age_range]; $kid_total += $ratio * $adult_price_per_night * $nights; } } // 累加单房型总价到总金额 $total_price += $adult_total + $kid_total; } return $total_price; }
四、优化建议
- 将价格配置移至CodeIgniter的
config目录下的自定义配置文件(如price_config.php),实现统一管理 - 添加数据校验逻辑:校验入住晚数为正、房型存在于价格配置中、成人/儿童数量为非负整数等,避免非法数据导致计算错误
- 若需支持节假日/旺季价格浮动,可扩展价格配置数组,增加日期维度的判断逻辑
内容的提问来源于stack exchange,提问作者Pawan Mall
相关产品推荐
相关产品推荐

