Magento – Magento 2, filter product collection by sku while preserving the given array sequence

collection;magento2product-collectionsequence

Using below code, collection is filtered. If $productSkus array is like

Array ( [0] => 5714156000153 [1] => 8690604469871 [2] => 6412616365413 )

after filtering I see the collection is in

Array ( [0] => 8690604469871 [1] => 5714156000153 [2] => 6412616365413 )

sequence. How to do filtering with respect to given sequence?

$collection ->addAttributeToSelect('*')
            ->addAttributeToFilter('sku', array('in' => $productSkus));

Best Answer

You can try this way.

  $collection ->addAttributeToSelect('*')
              ->addAttributeToFilter('sku', array('in' => $productSkus))
              ->addAttributeToSort('sku'); 

It defaults to ASC and use addAttributeToSort('sku', 'desc') for DESC.