Jump to content

Change order of items in WireArray


Robin S
 Share

Recommended Posts

I want to reorder my Pageimages array so that portrait-format images are placed last. Currently I'm removing portrait-format images and then adding them back.

$listing_images = $page->listing_images;
foreach($listing_images as $listing_image) {
    /* @var Pageimage $listing_image */
    if($listing_image->height() > $listing_image->width()) {
        $listing_images->remove($listing_image);
        $listing_images->add($listing_image);
    }
}

This works, but just wondering if there is some better WireArray method I could use that works like "move this item to the end of the array".

Link to comment
Share on other sites

You could skip the removal with most WireArray instances, as duplications are prevented by the item keys (filename in this case). There's also insertBefore() and insertAfter() and you could use all the array sorting functions if really needed:

$a = $wireArray->getArray();
sort($a)
$wireArray->setArray($a);

 

  • Like 1
Link to comment
Share on other sites

I am not sure if WireArray::sort() handles runtime vars. Try it out.

foreach ($page->listing_images as $image) $image->aspectRatio = $image->width/$image->height;
$page->listing_images->sort('aspectRatio');

 

  • Like 1
Link to comment
Share on other sites

57 minutes ago, LostKobrakai said:

You could skip the removal with most WireArray instances

Thanks, this works well. Short and sweet so will go with this.

 

1 hour ago, kixe said:

I am not sure if WireArray::sort() handles runtime vars. Try it out.

It does work, thanks. Although in my case I don't want to change the sort order beyond moving portrait images to the end so modified it to:

foreach($page->listing_images as $image) {
    if($image->height() > $image->width()) {
        $image->aspect = 2;
    } else {
        $image->aspect = 1;
    }
}
$page->listing_images->sort('aspect');

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...