I am facing some weird issue in the magento2 collection.
function to get item collection
public function getNewItems()
{
if ($this->_productsCache === null)
{
$items = $this->promoRegistry->getLimits();
$groups = $items['_groups'];
unset($items['_groups']);
if (!$items && !$groups) {
$this->_productsCache = false;
return false;
}
$allowedSku = array_keys($items);
foreach ($groups as $rule) {
$allowedSku = array_merge($allowedSku, $rule['sku']);
}
$products = $this->_productFactory->create()->getCollection()
->addAttributeToSelect(['name', 'small_image', 'status', 'visibility'])
->addFieldToFilter('sku', ['in' => $allowedSku])
;
foreach ($products as $key => $product) {
if (!in_array($product->getTypeId(), $this->_allowedTypes)) {
$this->promoMessagesHelper->showMessage(__(
"We apologize, but products of type <strong>%1</strong> are not supported",
$product->getTypeId()
));
$products->removeItemByKey($key);
}
if ($product->getTypeId() == 'simple' && (!$product->isInStock() || !$product->isSalable()
|| !$this->promoCartHelper->checkAvailableQty($product, 1))
) {
$this->promoMessagesHelper->addAvailabilityError($product);
$products->removeItemByKey($key);
}
foreach ($product->getProductOptionsCollection() as $option) {
$option->setProduct($product);
$product->addOption($option);
}
}
$allowedSku = "'" . str_replace(",", "','", implode(',',$allowedSku)) . "'";
$products->getSelect()->order(new \Zend_Db_Expr("FIELD(sku,$allowedSku)"));
if (sizeof($products) > 0) {
$this->_productsCache = $products;
}
else {
$this->_productsCache = false;
}
}
return $this->_productsCache;
}
Here the issue is that when i print collection data it showing in right ordering. But when i try to render it render in different order.
when $products->getData
Array
(
[0] => Array
(
[entity_id] => 3695
[attribute_set_id] => 4
[type_id] => simple
[sku] => 1059005
[has_options] => 0
[required_options] => 0
[created_at] => 2018-01-17 16:06:33
[updated_at] => 2019-06-26 13:58:53
[is_salable] => 1
)
[1] => Array
(
[entity_id] => 4026
[attribute_set_id] => 4
[type_id] => simple
[sku] => 1059010
[has_options] => 0
[required_options] => 0
[created_at] => 2018-01-17 16:13:17
[updated_at] => 2019-06-26 13:59:55
[is_salable] => 1
)
[2] => Array
(
[entity_id] => 6283
[attribute_set_id] => 4
[type_id] => simple
[sku] => 1049046
[has_options] => 0
[required_options] => 0
[created_at] => 2019-04-23 13:05:24
[updated_at] => 2019-06-26 14:02:46
[is_salable] => 1
)
[3] => Array
(
[entity_id] => 3897
[attribute_set_id] => 4
[type_id] => simple
[sku] => 1059008
[has_options] => 0
[required_options] => 0
[created_at] => 2018-01-17 16:10:32
[updated_at] => 2019-06-26 13:59:32
[is_salable] => 1
)
)
when foreach
through each item
$products = $block->getItems();
foreach ($products as $product) {
echo $product->getId().'<br>';
}
4026
3695
3897
6283
Notice ordering of Id Here in foreach printing
$collection->getData()
and create object in loop.Not the right way to do