You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据商品价格设置价格筛选上限,合并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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 23:12:01