Home > Blockchain >  laravel - Can I add new items to an array that already has some existing items?
laravel - Can I add new items to an array that already has some existing items?

Time:10-24

var_export($response) is an array like below:

array (
   0 =>
    array (
    'courseId' => 14,
    'tutorName' => 'admin',
    ),
   1 =>
    array (
    'courseId' => 15,
    'tutorName' => 'merl',
    ),
 )

The below code gives a result like this: "data": 3. I wanted add a new item called points with the $response array, into all elements. But here, it overwrites the existing array. How can I achieve this?

$dat=array_push($response,array('points'=>"3"));
return response()->json(['data' => $dat], 200);

Expected output:

[
    {
        "courseId": 14,
        "tutorName": "admin",
        "points": 3
    },
    {
        "courseId": 15,
        "tutorName": "merl",
        "points": 3
    }
]

CodePudding user response:

As mentioned, array_push() returns the new number of elements in the array. That's why you get 3.

You can add your value in all elements of the current response, like this:

foreach ($response as $key => $value) {
    $response[$key]['points'] = 3;
}

Then, just return the response :

return response()->json($response, 200);
  • Related