Laravel Blade模板中如何遍历键名规则一致的数组元素
解决方案
你原始写法不生效是因为PHP中动态拼接键名不能直接用$absences.$i这种字符串拼接语法,需要先构造完整的键名再取值,同时要做空数组判定避免下标越界报错。
实现方式1:固定遍历absences1到absences5
适合键名规则固定为1-5的场景:
@for ($i = 1; $i <= 5 ; $i++) @php // 构造完整键名 $key = "absences{$i}"; // 兼容数组/对象两种数据格式,空值默认返回空数组 $currentList = $absences->$key ?? $absences[$key] ?? []; @endphp {{-- 空数组直接跳过,避免报错 --}} @if(empty($currentList)) @continue @endif @php // 取公共字段,加空判定避免字段不存在报错 $course = $currentList[0]->subj ?? ''; $teacher = $currentList[0]->teacher ?? ''; @endphp {{-- 此处替换为你需要的HTML结构 --}} <div class="absence-group"> <h4>课程:{{ $course }} 授课教师:{{ $teacher }}</h4> <ul> @foreach($currentList as $item) <li>学生姓名:{{ $item->name }} 年级:{{ $item->stage }} 分组:{{ $item->group }}</li> @endforeach </ul> </div> @endfor
实现方式2:自动匹配所有absences开头的键
后续新增absences6、absences7等键时不需要修改代码,灵活性更高:
@php // 过滤出所有键名以absences开头的数据集 $allAbsenceGroups = collect($absences)->filter(function ($value, $key) { return str_starts_with($key, 'absences'); }); @endphp @foreach($allAbsenceGroups as $currentList) @if(empty($currentList)) @continue @endif @php $course = $currentList[0]->subj ?? ''; $teacher = $currentList[0]->teacher ?? ''; @endphp {{-- 此处替换为你需要的HTML结构 --}} <div class="absence-group"> <h4>课程:{{ $course }} 授课教师:{{ $teacher }}</h4> <ul> @foreach($currentList as $item) <li>学生姓名:{{ $item->name }} 年级:{{ $item->stage }} 分组:{{ $item->group }}</li> @endforeach </ul> </div> @endforeach
注意事项
- 代码中使用
??做空值兼容,对应字段不存在、数组为空时不会抛出异常 - 如果确定你从控制器传入的
$absences是数组格式,可直接简化为$currentList = $absences[$key] ?? [];如果是对象格式,简化为$currentList = $absences->$key ?? []即可
内容的提问来源于stack exchange,提问作者Sermed mayi
相关产品推荐
相关产品推荐

