Shift first Structure item to end

Is there a simple way to move the first item inside a structure field to the last position before looping over it in a template while keeping it an Object? I can convert it to an array but then things get messy inside the iteration.

Thanks.

Yes, like this:

$items= page('somepage')->myStructureField()->toStructure()->offset(1);
$key = $items->count();
$firstItem =  page('somepage')->myStructureField()->toStructure()->first();
$allItems = $items->append($key, $firstItem);
2 Likes

Thanks. Perfect solution, thanks.

Oops, I mean that I needed to move the last item to be the first. Adjusted your code and got close:

$gallery     = $page->gallery()->toStructure();
$last        = $gallery->last();
$gallery     = $gallery->prepend(-1, $last);

This caused the last item to be duplicated, so I tried the following but it’s giving an error:

foreach ($gallery->not($last) as $item) {

Also question about ->prepend(). If the purpose is to add to the beginning, why do you need to define the key? It would always be at the beginning. If I set to 0, it removes the first item.

It doesn’t. work without a key, but you can still use the $key variable from above:

<?php
$options = $page->gallery()->toStructure();

$key = $options->count();
$lastItem =  $options->last();
$options = $options->limit($key-1);
$newItems = $options->prepend($key, $lastItem);
foreach($newItems as $item) {
  echo $item->title();
}

Thanks. What about removing the last item to prevent duplication from above?

What do you mean by “removing”?

After prepending the last item to first, the original still remains in the last position. I tried ->not($last) but that doesn’t work.

I don’t understand, with the above example, you always have 4 items, nothing duplicated. I limit the original collection to anything but the last item. Then I prepend the last. item.

Apologies, I overlooked your addition of limit().

Similar question, but with pages collection: Move page of collection to last position

2 Likes