Reputation: 3993
I have a multi-dimensional array being passed from a 3rd party source which I'm turning into an Illuminate Collection object and doing a group-by.
So it is retuning me the data like so:
{
#items: array:2 [
"123H0002" => Collection{
#items: array:1 [
0 => array:12 [
"account" => "12345",
"id" => "456",
"name" => "Dave",
...
]
]
}
"456854456456" => Collection{
#items: array:1 [
0 => array:12 [
"account" => "4657456",
"id" => "123",
"name" => "Geoff",
...
]
]
}
]
}
I'm then looping over this to process each group of collections together.
foreach($data as $items){
$this->process($items)
}
Then inside of the process method, I want to add items to the array inside of the collection but it seems to fail to save.
public function process($data)
{
foreach($data as $item){
$item['status'] = 'NEW';
}
$this->db->insert_batch('imported_data', $data->toArray());
}
Now the problem here is $item['status'] is there when I debug the contents of the $item array inside of the foreach loop however this change isn't reflected in the final $data collection when its converted to an array.
What am I missing for updating an array inside of a collection?
Upvotes: 1
Views: 4275
Reputation: 409
U can´t update the array cause is passed by value, for modify the content u need pass by reference like this:
foreach($data as &$item){
$item['status'] = 'NEW';
}
don´t forget to unset the reference:
unset($item);
I think it's best to avoid this pitfall altogether and just write foreach loops that have to manipulate the original array the normal way:
foreach($data as $index => $entry) {
$data[$index] = ...
}
here you will get more info about reference variables.
Upvotes: 2