[英]Laravel collection increment values and keys
Hello, 你好,
How do I decrement
all keys from a collection and convert it to an array? 如何
decrement
集合中的所有键并将其转换为数组?
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. 您可以通过遍历现有集合并将键分配为与当前键-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 从所需的描述输出中,您似乎可以使用本机PHP函数array_values
returns all the values from the array and indexes the array numerically.
返回数组中的所有值,并对数组进行数字索引。
http://php.net/manual/en/function.array-values.php http://php.net/manual/en/function.array-values.php
array_values($collection->toArray())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.