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

Laravel Livewire数组分组求助:按指定数组值分组展示表格数据

Laravel Livewire 数组分组解决方案

步骤1:在组件中添加分组计算属性

在你的Livewire组件里,新增一个计算属性,用于将item_id和group按组归类,同时保证分组展示顺序一致:

public function getGroupedItemsProperty()
{
    $grouped = [];
    
    // 遍历输入项,按组整理数据
    foreach ($this->inputs as $index) {
        // 跳过无效索引,避免报错
        if (!isset($this->group[$index]) || !isset($this->item_id[$index])) {
            continue;
        }
        
        $groupName = $this->group[$index];
        $grouped[$groupName][] = [
            'item_id' => $this->item_id[$index]
        ];
    }
    
    // 按组名排序,确保分组展示顺序稳定
    ksort($grouped);
    
    return $grouped;
}

步骤2:修改视图渲染逻辑

替换原有的表格遍历代码,改为遍历分组后的数据,先渲染组标题,再渲染组内的每一项:

<tbody class="text-xs divide-y divide-gray-100 ">
    @forelse ($groupedItems as $groupName => $items)
        <!-- 组标题行 -->
        <tr class="bg-gray-50">
            <td colspan="2" class="p-2 font-medium">
                {{ $groupName }}
            </td>
        </tr>
        
        <!-- 组内数据行 -->
        @foreach ($items as $item)
            <tr>
                <td class="p-2"></td> <!-- 不需要重复显示组名时,此处留空 -->
                <td class="p-2">
                    {{ $item['item_id'] }}
                </td>
            </tr>
        @endforeach
    @empty
        <tr>
            <td colspan="2" class="p-2 text-center">暂无数据</td>
        </tr>
    @endforelse
</tbody>

步骤3:完善动态添加项的逻辑

为了避免新增项时出现索引不存在的问题,修改addLine方法,初始化对应索引的group和item_id值:

public function addLine($i)
{
    $i = $i + 1;
    $this->i = $i;
    array_push($this->inputs, $i);
    
    // 初始化新项的组和ID字段,防止索引越界报错
    $this->group[$i] = '';
    $this->item_id[$i] = '';
}

这样就能实现按组展示数据,每组顶部显示组名标题,且动态添加的项也会自动归类到对应分组中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 11:20:35