简体   繁体   中英

Access data in multidimensional array

I am trying to get all data i need in one variable

--Subject

---Chapters related to subject

----Topics related to chapter

And this is what i have done!

    $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;
    }

When i dd() in laravel, i see all the data arranged in structure i wanted. The problem comes when accessing a specific data like so,

    @foreach($subjects as $subject)
        {{ $subject->name }}
        {{ $subject->related_chapters[0]['name'] }}
    @endforeach

i get an error:

    Undefined offset: 0 

Is there a better way of structuring my array, and getting data correctly. Please help!

Undefined offset is an notice that comes when you try to access an array which does not exist . Make sure that a value exists in that index or you can do something like this just before accessing the value

If (isset ( $subject->related_chapters[0]['name']))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM