Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel collection .each() + array_push

Tags:

php

laravel-5

need help regarding array_push inside .each() method on laravel. I cannot get the container array on this code:

$imagesData = array();
collect($data['images'])->each(function($v, $k) use($imagesData){

    $v['created_at'] = date('Y-m-d H:i:s');
    $v['updated_at'] = date('Y-m-d H:i:s');
    $v['image_id'] = $v['image_id'];
    $v['settings'] = json_encode($v['settings']);

    array_push($imagesData, $v);

});

$result = Images::insert($imagesData, true);

Basically, the code above I want to iterate the data inside .each() and then push it to array container and insert it by batch. NOTE: when i use foreach there will be no problem, but I need to use .each() instead of foreach.

Thanks

like image 972
Cris Avatar asked Mar 13 '17 21:03

Cris


People also ask

How to append array to array PHP?

Given two array arr1 and arr2 and the task is to append one array to another array. Using array_merge function: This function returns a new array after merging the two arrays. $arr1 = array ( "Geeks" , "g4g" );

How to push array object in PHP?

Just do: $object = new stdClass(); $object->name = "My name"; $myArray[] = $object; You need to create the object first (the new line) and then push it onto the end of the array (the [] line).


2 Answers

Because you want to change the original $imageData, you need to refer to this variable instead of just copying the value of it. This is done by using an ampersand &.

collect($data['images'])->each(function($v, $k) use(&$imagesData){
    // ...
});
like image 166
manniL Avatar answered Nov 01 '22 20:11

manniL


Using the Collection::map method is a much more readable way to do the same thing:

$imagesData = collect($data['images'])
    ->map(function($item) {

        $item['created_at'] = date('Y-m-d H:i:s');
        $item['updated_at'] = date('Y-m-d H:i:s');
        $item['image_id'] = $item['image_id'];
        $item['settings'] = json_encode($item['settings']);

        return $item;
    })
    ->all();

$result = Images::insert($imagesData, true);

map iterates over the array the same way as each does. The difference is that each does not return anything (so you need to build the new array yourself) while map automatically builds a new collection of the items you return inside the function. After map, you use all to return the results as a plain array.

like image 17
Moshe Katz Avatar answered Nov 01 '22 19:11

Moshe Katz