Hi mates, Here I wanna use map function and wanna append 3rd party API response to the students['subjects'] array. how can I achieve that? also, tried like this but not getting the expected output? Any help that would be great. Thanks!
$students = Student::all()->toArray();
foreach ($students as $student) {
(collect($student['subjects']))->map(function ($item) {
if ($item['sub_id']) {
//create empty array for subj
$item['subj'] = [];
//3rd party API
$item['subj'] = API::Getsubjs(sub_id);
} else {
$item['subj'];
}
array_merge($students['subjects'], $item);
});
}
@deepu07 you cannot use $students within the map closure unless you pass it using use. But then just returning the modified array wouldn't it be sufficient, as that's what map is for :
The map method iterates through the collection and passes each value to the given callback. The callback is free to modify the item and return it, thus forming a new collection of modified items
So try this instead:
foreach ($students as $student) {
$student['subjects'] = (collect($student['subjects']))->map(function ($item) {
if ($item['sub_id']) {
//create empty array for subj
$item['subj'] = [];
//3rd party API
$item['subj'] = API::Getsubjs($item['sub_id']);
}
return $item;
});
}