Devidas
Devidas

Reputation: 181

how to shift first element of array to the last?

We have to show the first element of the array to the last Check below code

public function getFilters(\Magento\Catalog\Model\Layer $layer)
{
    if (!count($this->filters)) {
        $this->filters = [
            $this->objectManager->create(
                $this->filterTypes[self::CATEGORY_FILTER], 
                ['layer' => $layer]
            ),
        ];
        foreach ($this->filterableAttributes->getList() as $attribute) {
            $this->filters[] = $this->createAttributeFilter($attribute, $layer);
        }
    }
    return $this->filters;
}

The result of $this->filters will look like

$this->filters[0] = Magento\CatalogSearch\Model\Layer\Filter\Category
$this->filters[1] = Magento\CatalogSearch\Model\Layer\Filter\Attribute
$this->filters[2] = Magento\CatalogSearch\Model\Layer\Filter\Attribute
$this->filters[3] = Magento\CatalogSearch\Model\Layer\Filter\Attribute
$this->filters[4] = Magento\CatalogSearch\Model\Layer\Filter\Attribute

How to move it?

Upvotes: 1

Views: 251

Answers (2)

Serge Fonville
Serge Fonville

Reputation: 326

It depends, do you want to swap the first and last element, or would you want to remove the element from the end of the array and prepend it to the beginning (effectively having moved all elements on further). For the former, you could use (as mentioned at Swap array values with php)

$temp = $filters[0];
$a[0] = $filters[count($filters) - 1];
$a[1] = $temp;

For the latter you could use:

$first_element = array_unshift($filters)
array_push($first_element)

Upvotes: 0

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72269

You can use array_shift() for this:

$data = array_shift($this->filters);
$this->filters[]=  $data;

Sample output:- https://3v4l.org/WULpM

Upvotes: 4

Related Questions