如何根据商品价格设置价格筛选上限,合并options为单个价格区间
价格筛选区间合并实现方案
实现逻辑
- 遍历原
options数组所有子项,累加所有count字段值得到总商品数量 - 提取每个价格区间的上限(取
value字段_后面的数值,也可以取label字段-后面的数值),取所有上限的最大值作为合并后区间的上限 - 将原
options字段替换为仅包含单个合并后区间的数组
PHP实现代码
// 原数据,可替换为实际业务中获取到的价格筛选数组 $priceFilter = [ 'label' => 'Price', 'count' => 5, 'attribute_code' => 'price', 'options' => [ ['label' => '0-100', 'value' => '0_100', 'count' => 2208], ['label' => '100-200', 'value' => '100_200', 'count' => 338], ['label' => '200-300', 'value' => '200_300', 'count' => 16], ['label' => '300-400', 'value' => '300_400', 'count' => 1], ['label' => '400-500', 'value' => '400_500', 'count' => 1], ] ]; $totalCount = 0; $maxPrice = 0; foreach ($priceFilter['options'] as $option) { // 累加所有区间的商品总数 $totalCount += $option['count']; // 提取当前区间的价格上限 $currentMax = explode('_', $option['value'])[1]; if ($currentMax > $maxPrice) { $maxPrice = $currentMax; } } // 替换原options为合并后的单区间数组 $priceFilter['options'] = [ [ 'label' => "0-{$maxPrice}", 'value' => "0_{$maxPrice}", 'count' => $totalCount ] ]; // 打印验证处理结果 print_r($priceFilter);
输出效果
处理后得到的数组完全匹配预期格式:
Array ( [label] => Price [count] => 5 [attribute_code] => price [options] => Array ( [0] => Array ( [label] => 0-500 [value] => 0_500 [count] => 2564 ) ) )
内容的提问来源于stack exchange,提问作者devhs
相关产品推荐
相关产品推荐

