【问题标题】:Combine two Laravel collections with alternating rows将两个 Laravel 集合与交替行组合
【发布时间】:2019-07-22 21:04:42
【问题描述】:
我有两个 Laravel 集合,它们是数据库查询的结果(使用 Eloquent ORM)。
我希望合并这两个集合,每个集合的行交替排列。
所以如果集合 1 是:
一、二、三、四
集合 2 是:
土豚,瓶子,猫,狗
结果将是:
一、土豚、二、瓶、三、猫、四、狗。
也可以选择一次交替使用两个(或三个),例如
一、二、土豚、奶瓶、三、四、猫、狗。
谢谢。
【问题讨论】:
标签:
php
mysql
database
laravel
【解决方案1】:
如果您已经拥有这些集合,可能最简单的方法就是循环它们并添加到新的集合或数组中。这使您可以很好地控制一次交替两个或三个或其他任何东西的能力:
由于看不到你的代码,我就放一个伪代码示例来帮助说明:
alternator = 1;
choiceOfAlternate = 3; // Every third for example on this second array/collection
arrayOfStuff = [];
for (loop = 1; loop < size of collection; loop ++){
if(choiceOfAlternate === 3){ // You could use mod here too, just showing simplest
arrayOfStuff[] = [itemAtIndex*loop*OfFirstCollection, itemAt*Alternator*OfSecondCollection];
choiceOfAlternate = 1; // start your alternate loop again
alternator ++; // So you have an index on the second collection that doesn't start over
}else{
// You'll have to decide if you want an array in here, or null, or whatever
arrayOfStuff[] = [itemAtIndex*loop*OfFirstCollection, ''];
choiceOfAlternate ++;
}
给这只猫剥皮的方法有很多,但有时老派的方法最容易遵循。