Reputation: 13172
If I dd($items)
, the result like this :
I want to add number to each array
So the first array, exist key number with value 1
The second array, exist key number with value 2
etc
I try like this :
$items->map(function ($item) {
$item['number'] = 1;
return $item;
});
Number does not increase. I'm confused to make the counter
How can I solve this problem?
Upvotes: 2
Views: 3983
Reputation: 8287
You can try it like this
$newItems = $items->map(function ($item, $index) {
$item['number'] = $index + 1;
return $item;
});
Edit: Based on comment (I don't recommend it because then you can not get benefit of eloquent model. It simply return you an array )
$newItems = $items->map(function ($item, $index) {
$number = ['number' => $index + 1];
return $number + $item->toArray();
});
Upvotes: 6
Reputation: 369
you can use array_merge
$newItems = $items->map(function ($item, $index) {
return array_merge(array("number" => $index + 1), $item);;
});
Upvotes: 0
Reputation: 1013
$counter=1;
$items->map(function ($item) use(&$counter){
$item['number'] = $counter++;
return $item;
});
Upvotes: 0