3

I try to list all product names in a store, so I try the following code.

$collection = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*')->setPageSize(5000)->setCurPage(1);

$collection->addAttributeToFilter('status', Mage_Catalog_Model_Product_Status::STATUS_ENABLED);

foreach ($collection as $product) {
    echo $product->getName();
    echo "<br>";
}

This gives the following result.

Without sort

After that I try to sort this. The code is:

$collection = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*')->setPageSize(5000)->setCurPage(1);
$collection->addAttributeToFilter('status', Mage_Catalog_Model_Product_Status::STATUS_ENABLED);

foreach ($collection as $product) {
    $pro[] = $product->getName();
}

sort($pro);

foreach ($pro as $pr) {
    echo  $pr; echo"<br>";
}

This gives the following result.

With Sort

It gives two lists in ascending order.

Why does it behave like this?

I need only one list with ascending order for that. What should I do?

0

2 Answers 2

6

The reason you got two lists with ascending order is because of PHP sort() function. The default sorting behavior for this function is non-natural ordering, so it gives you unpredictable results. Try natcasesort() instead of sort(). See more detail about PHP sort() on below link:

http://php.net/manual/en/function.sort.php

OR

try to sorting your collection through Magento addAttributeToSort collection method, see below code for reference:

$collection = Mage::getModel('catalog/product')
                         ->getCollection()
                         ->addAttributeToSort('name', 'ASC');

Hope this will clear your doubt.

3

Try this code :

<?


$collection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('*')
->addAttributeToSort('name','ASC') // for name
->setPageSize(5000)->setCurPage(1);

?>

For other field use : ->addAttributeToSort('field','ASC') Hope it will work for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.