访问多维数组中的数据
Access data in multidimensional array
我试图在一个变量中获取我需要的所有数据
--主题
---与主题相关的章节
----与章节相关的主题
这就是我所做的!
$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
是否有更好的方法来构造我的数组并正确获取数据。请帮忙!
未定义的偏移量是当您尝试访问不存在的数组时出现的通知。确保该索引中存在一个值,或者您可以在访问该值之前执行类似的操作
If (isset ( $subject->related_chapters[0]['name']))
我试图在一个变量中获取我需要的所有数据
--主题
---与主题相关的章节
----与章节相关的主题
这就是我所做的!
$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
是否有更好的方法来构造我的数组并正确获取数据。请帮忙!
未定义的偏移量是当您尝试访问不存在的数组时出现的通知。确保该索引中存在一个值,或者您可以在访问该值之前执行类似的操作
If (isset ( $subject->related_chapters[0]['name']))