Hello,
How do I decrement all keys from a collection and convert it to an array?
So let's say I've a collection that looks like this:
Collection {#410 ▼
#items: array:1 [▼
1 => 1,
2 => 6
]
}
I need that to convert like this:
array:1 [▼
0 => 1,
1 => 6
]
I know I can do:
$collection->toArray();
But than I get this:
array:1 [▼
1 => 1
]
I already looked at the docs but can't find it!
You can just make a new array from the collection by looping over the existing collection and assigning the key to be the same as the current key -1.
$newCollection = collect([]);
$collection->each(function($item, $key) use ($newCollection) {
$newCollection->put($key-1, $item);
});
//$newCollection has decremented keys
From the described desired output it looks like you can use native PHP function array_values which
returns all the values from the array and indexes the array numerically.
http://php.net/manual/en/function.array-values.php
array_values($collection->toArray())