Is there an easy way to merge two Page Arrays the following way:
Array One: X X X X X
Array Two: O O O O O
Mixed: X O X O X O X O X O
So far I’ve tried
$mixed = new Pages(array($one, $two));
$mixed = $one->merge($two);
Both of them just append one array after the other.
Mixed: X X X X X O O O O O
Any idea for a simple solution?
With a simple for
-loop? I don’t know of any other solution…
$merged = [];
for ($i=0; $i < count($one); $i++){
$merged[] = $one[$i];
$merged[] = $two[$i];
}
You should make sure that $one
and two
both have the same length.
Thanks.
I get the following error trying that:
Fatal error: Cannot use object of type Children as array
Thanks.
I get the following error:
Warning: array_shift() expects parameter 1 to be array, object given
Try to convert the page collection to array first:
$one = $page->children()->toArray();
// etc.
Not tested.
got that far earlier, but couldn’t figure out how to create pages out of the array again. Any idea?
fvsch
May 4, 2016, 8:08pm
9
No need to convert to an array, since the class used for page collections already has methods for iterating and getting pages from a collection.
https://getkirby.com/docs/cheatsheet/pages/nth
For instance, as a controller:
<?php
return function($site, $pages, $page) {
$collection = pages();
$group1 = $site->find('section1')->children()->limit(10);
$group2 = $site->find('section2')->children()->limit(10);
$max = max($group1->count(), $group2->count());
for ($i = 0; $i < $max; $i++) {
if ($p1 = $group1->nth($i)) {
$collection->add($p1);
}
if ($p2 = $group2->nth($i)) {
$collection->add($p2);
}
}
return ['collection' => $collection];
};
2 Likes