Laravel Collection 键修改

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40568745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:44:11  来源:igfitidea点击:

Laravel Collection keys modification

phparrayslaravel

提问by pavon147

I use filtermethod from Collectionclass to remove some objects from collection. But after that operation, sometimes objects with keys eg. 1, 4, 5 left. I would like to always have elements with order 0, 1, 2, 3 etc. after filteraction.

我使用类中的filter方法Collection从集合中删除一些对象。但是在那次操作之后,有时带有键的对象,例如。还剩 1、4、5 个。我希望在操作后始终具有顺序为 0、1、2、3 等的元素filter

Is there any elegant way to do it without rewriting table to a new one?

有没有什么优雅的方法可以在不将表重写为新表的情况下做到这一点?

Thanks!

谢谢!

回答by Saumya Rastogi

You can use Laravel Collection's values()method to make the the keys of a collection in a serialized order like this:

您可以使用 Laravel Collection 的values()方法以这样的序列化顺序制作集合的键:

// Just for demonstration
$collection = collect([
    10 => ['fruit' => 'Apple', 'price' => 200],
    11 => ['fruit' => 'Mango', 'price' => 500]
]);

$values = $collection->values();

$values->all();

/* Result would be:
    [
        0 => ['fruit' => 'Apple', 'price' => 200],
        1 => ['fruit' => 'Mango', 'price' => 500],
    ]
*/

Hope this helps!

希望这可以帮助!