I assume that size
is a dropdown attribute.
I'm not sure exactly how the sorting works but it can be one of the 2 cases.
Case 1.
The sorting is done via values of that attribute. And the actual values stored in the database for are integers. They are the ids of the options.
So most probably the id of the option 100g
is smaller than the id of the option 10g
and the sorting is done for these ids.
Case 2.
The sorting is done somehow by using the labels of the options.
In this case, what you see in the result is perfectly normal since the comparison is done for strings and the string 100g
is "smaller" than the string 10g
.
Either way, I propose you a solution that works in both cases.
Since you need only to display the labels somewhere, why not just collect the labels as you do now, add them to an array and then sort that array as you want.
Again, you might hit the problem that the array elements will be sorted as strings, but you can overcome this by removing g
from the end of each element, sorting then adding g
back.
Here is the code you can use.
It works for kg and g at the same time and it sorts them properly.
I mean 1500g comes between 1kg and 2kg.
if($_product->getTypeId() == "configurable"):
$conf = Mage::getModel('catalog/product_type_configurable')->setProduct($_product);
$simple_collection = $conf->getUsedProductCollection()->addAttributeToSelect('*')->addAttributeToSort('size','ASC')->addFilterByRequiredOptions();
$toSort = array();
foreach($simple_collection as $simple_product) {
$unit = trim($simple_product->getAttributeText('size'));
//check of it's kg unit
if (substr($unit, -2) == 'kg') {
$toSort[] = array(
'sort_value' => (float)str_replace('kg', '', $unit) * 1000,
'real_value' => $unit,
'product' => $simple_product
);
} else {
//it's gram unit
$toSort[] = array(
'sort_value' => (float)str_replace('g', '', $unit),
'real_value' => $unit,
'product' => $simple_product
);
}
}
usort($toSort, function($a, $b){
if ($a['sort_value'] == $b['sort_value']) {
return 0;
}
return ($a['sort_value'] < $b['sort_value']) ? -1 : 1;
});
foreach ($toSort as $item) {
/** @var Mage_Catalog_Model_Product $product */
$product = $item['product'];
//use getFinalPrice instead of price. Maybe there are discount rules applied to it.
echo $item['real_value'].': '.Mage::helper('core')->currency($product->getFinalPrice()).'<br />';
}
endif;
g
so it takes string instead of integercatalog->manage attribute
and search for size and change the dropdown option valueg
from name and your sort will work fine on frontend