Nastya Keller Nastya Keller - 6 months ago 32
PHP Question

Nested arrays in Laravel

I'm working with Laravel and trying to solve difficult situation with queries.

Anybody knows, why as a result I'm getting this? Trying to pass results of the first query to second.

Here's the first query. All looks good

$teach_id = auth()->id();
$cur_subj = DB::table('subject')->select('sId')->where('id', '=', $teach_id)->get();

array:3 [▼
0 => {#398 ▼
+"sId": "1"
}
1 => {#399 ▼
+"sId": "2"
}
2 => {#400 ▼
+"sId": "3"
}
]


Trying to pass this array to here

foreach ($cur_subj as $key => $value){
$studs[] = DB::table('stud')
->join('subject', 'stud.sId', '=', 'subject.sId')
->join('users', 'users.id', '=', 'stud.id')
->select('users.name', 'subject.sName')
->where('stud.sId', $value->sId)
->get();

}


As a result I see

array:3 [▼
0 => array:2 [▼
0 => {#403 ▼
+"name": "Багрянцев К. Н."
+"sName": "История"
}
1 => {#404 ▼
+"name": "Суворова Е. А."
+"sName": "История"
}
]
1 => array:1 [▼
0 => {#405 ▼
+"name": "Багрянцев К. Н."
+"sName": "Алгебра"
}
]
2 => []
]


Don't understand, why results of second query inserted in array from first query? How to fix this?

Answer

Because get returns collection, so $studs is array of collections

try

$studs = collect([]);
foreach ($cur_subj as $key => $value)
{
    $c = DB::table('stud')
                    ->join('subject', 'stud.sId', '=', 'subject.sId')
                    ->join('users', 'users.id', '=', 'stud.id')
                    ->select('users.name', 'subject.sName')
                    ->where('stud.sId', $value->sId)
                    ->get();
    $studs = $studs->merge($c);

}
Comments