Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

deepu07's avatar
Level 11

Array Map

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);
            });
        }
0 likes
5 replies
Nakov's avatar

@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;
    });
}
Tray2's avatar

What is your expected output and what does that code give you?

deepu07's avatar
Level 11

@nakov Thanks that works! also I wanna push result foreach $student into $students. how can I achieve that?

Nakov's avatar
Nakov
Best Answer
Level 73

@deepu07 just by replacing it I guess?

foreach ($students as $key => $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;
    });

    $students[$key] = $student;
}

this should override it.

Please or to participate in this conversation.