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

Laravel 8中筛选宽度≥100的商品数据并格式化展示方法

Laravel 8 商品维度筛选与格式化展示实现方案

需求概述

现有t_items(商品表)与t_dimensions(维度表),通过dimension_id关联。需完成两项核心操作:

  1. 筛选出宽度值≥100的商品数据
  2. 将商品size字段与对应维度表的dimension字段拆分匹配,按指定格式展示

现有代码与表结构

当前控制器代码

public function test(){
    // $item = '20/20/20';
    // $dimension = 'width/height/depth';
    $item = TestItem::join('t_dimensions','t_items.dimension_id', '=', 't_dimensions.id')->get();

    //foreach($item as $item){
        //$size = explode('/',$item->size);
        //$item = explode('/',$item->dimension);
    //}

    return response->json($item);
}

维度表(t_dimensions)

iddimension
1Height/Width
2Width/Height/Depth

商品表(t_items)

iditemsizedimension_id
1mistar20/51
2board50/1001
3board80/501
4pipe120/50/802
5plate200/1001

期望展示格式

  1. board Height 50, Width 100
  2. pipe Width 120, Height 50, Depth 80
  3. plate Width 200, Height 100

解决方案实现

核心思路

由于不同维度组的宽度位置不固定,无法直接通过SQL筛选,需先查询关联数据,再在PHP层面完成维度匹配、筛选与格式拼接。

修改后的控制器代码

public function test()
{
    // 查询关联数据,指定所需字段减少冗余
    $items = TestItem::join('t_dimensions', 't_items.dimension_id', '=', 't_dimensions.id')
        ->select('t_items.*', 't_dimensions.dimension')
        ->get();

    $filteredResult = [];
    foreach ($items as $item) {
        // 拆分维度与尺寸为数组
        $dimensionList = explode('/', $item->dimension);
        $sizeList = explode('/', $item->size);
        
        // 关联维度与尺寸,生成键值对映射
        $dimSizeMap = array_combine($dimensionList, $sizeList);
        
        // 检查宽度值是否符合要求(注意维度字段首字母大写)
        if (isset($dimSizeMap['Width']) && (int)$dimSizeMap['Width'] >= 100) {
            // 拼接指定格式的维度字符串
            $formattedDims = [];
            foreach ($dimSizeMap as $dim => $size) {
                $formattedDims[] = "$dim $size";
            }
            $formattedStr = implode(', ', $formattedDims);
            
            $filteredResult[] = [
                'name' => $item->item,
                'display_text' => "$item->item   $formattedStr"
            ];
        }
    }

    // 生成期望的有序列表格式输出
    $output = '';
    foreach ($filteredResult as $index => $data) {
        $output .= "> " . ($index + 1) . ". " . $data['display_text'] . "\n";
    }

    return response($output, 200, ['Content-Type' => 'text/plain']);
    // 若需返回JSON,替换为:return response()->json($filteredResult);
}

代码说明

  1. 查询优化:通过select指定字段,避免查询不必要的数据
  2. 维度映射:使用array_combine将维度与尺寸数组关联,快速定位宽度值
  3. 筛选逻辑:判断宽度数值是否≥100,仅保留符合条件的商品
  4. 格式拼接:遍历维度映射,拼接成指定格式的字符串,最终生成有序列表输出

内容的提问来源于stack exchange,提问作者rista

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 17:20:36