php 将 Laravel 集合附加到另一个集合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42494732/
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-08-26 02:36:40  来源:igfitidea点击:

Append a Laravel collection with another collection

phparrayslaravellaravel-5

提问by tronic

I am trying to append an Eloquent collection with another Eloquent collection in Laravel 5.3.

我正在尝试在 Laravel 5.3 中附加一个 Eloquent 集合和另一个 Eloquent 集合。

This is what I've done so far:

这是我到目前为止所做的:

$entries = Entry::all();
$posts   = Post::all();

$entries->merge($posts);

I tried to use merge()as shown in the code above, but it seems that I'm stuck with this kind of problem (since some of them have the same idwith the same value):

我尝试使用merge()上面代码中所示的方法,但似乎我遇到了这种问题(因为其中一些具有id相同的值):

Collection merge eating up some rows

集合合并占用了一些行

Any ideas?

有任何想法吗?

回答by Bj?rn

I believe you can merge the two eloquent collections like this:

我相信你可以像这样合并两个雄辩的集合:

$mergedCollection = $entries->toBase()->merge($posts);

After this it is a collectionwith all entries.

在此之后,它是包含所有条目的集合

回答by Jason

I believe you may be looking for concat(). This will append one container to the end of another container, regardless of the keys of either.

我相信您可能正在寻找concat(). 这会将一个容器附加到另一个容器的末尾,而不管其中任何一个的键。

$entries->concat($posts);

回答by Yevgeniy Afanasyev

if you need to merge big_products and small_products:

如果您需要合并 big_products 和 small_products:

$products = $bigProducts->values()->merge($smallProducts->values());

The merge method merges the given array or collection with the original collection. If a string key in the given items matches a string key in the original collection, the given items's value will overwrite the value in the original collection.

merge 方法将给定的数组或集合与原始集合合并。如果给定项中的字符串键与原始集合中的字符串键匹配,则给定项的值将覆盖原始集合中的值。

But

If the given items's keys are numeric, the values will be appended to the end of the collection:

如果给定项的键是数字,则值将附加到集合的末尾:

Thus, all you need is to get rid of keys and you can do it with ->values()function.

因此,您所需要的只是摆脱键,您可以使用->values()功能来做到这一点。

Tested on Laravel-6

在 Laravel-6 上测试

回答by Jeff

The merge() method receives an array, so you have to do something like

merge() 方法接收一个数组,所以你必须做类似的事情

$entries->merge($posts->toArray());

Laravel Collections: merge() method

Laravel 集合:merge() 方法