我试图在一个变量
中获取我需要的所有数据- 主题
---与主题相关的章节
----与章节相关的主题
这就是我所做的!
$subjects = Subject::all();
$chapters = Chapter::all();
$topics = Topic::all();
foreach ($subjects as &$subject)
{
$i = 0;
$subject->related_chapters = array();
$chapters_reltn = array();
foreach ($chapters as $chapter)
{
if ($chapter->subject_id == $subject->id)
{
$chapters_reltn[$i]['id'] = $chapter->id;
$chapters_reltn[$i]['name'] = $chapter->name;
$j = 0;
foreach ($topics as $topic)
{
if ($topic->chapter_id == $chapter->id)
{
$chapters_reltn[$i]['related_topics'][$j]['id'] = $topic->id;
$chapters_reltn[$i]['related_topics'][$j]['name'] = $topic->name;
$j++;
}
}
$i++;
}
};
$subject->related_chapters = $chapters_reltn;
}
当我在laravel中dd()时,我看到所有数据按照我想要的结构排列。 访问特定数据时会出现问题,
@foreach($subjects as $subject)
{{ $subject->name }}
{{ $subject->related_chapters[0]['name'] }}
@endforeach
我收到错误:
Undefined offset: 0
是否有更好的方法来构建我的数组并正确获取数据。请帮忙!
答案 0 :(得分:1)
未定义的偏移量是当您尝试访问不存在的数组时出现的通知。确保该索引中存在值,或者您可以在访问值
之前执行此类操作if(isset($ subject-> related_chapters [0] ['name']))