I have an array $data['products'][] = array()
which is getting data from Database. Now i want to sort this array based on the [catname]
.
That is all similar [catname]
to be grouped/sorted. for ex. all cactus related product to be first and then Special sweets
My Array
$data['products'][] = array(
'product_id' => $result['product_id'],
'name' => $result['name'],
'catname' => $result['catname'],
'description' => utf8_substr(trim(strip_tags(html_entity_decode($result['description'], ENT_QUOTES, 'UTF-8'))), 0, $this->config->get('theme_' . $this->config->get('config_theme') . '_product_description_length')) . '..',
'price' => $price,
);
What i tried is using usort()
function build_sorter($key) {
return function ($a, $b) use ($key) {
return strnatcmp($a[$key], $b[$key]);
};
}
usort($array, build_sorter('catname'));
foreach ($array as $item) {
echo $item['product_id'] . ', ' . $item['catname'] . "\n";
}
but it is not sorting as desired. Kindly help in getting this correct.
Current ARRAY
Array
(
[0] => Array
(
[product_id] => 119
[name] => Product 1
[catname] => Special Sweets
[description] => This is a sweet
[price] => $0.00
)
[1] => Array
(
[product_id] => 56
[name] => Product 2
[catname] => cactus
[description] => description goes here..
[price] => $0.00
)
[2] => Array
(
[product_id] => 59
[name] => Product 3
[catname] => Special Sweets
[description] => Corn goes here con..
[price] => $0.00
)
[3] => Array
(
[product_id] => 79
[name] => Product 4
[catname] => cactus
[description] => cactus goes here con..
[price] => $0.00
)
)
DESIRED ARRAY
Array
(
[0] => Array
(
[product_id] => 56
[name] => Product 2
[catname] => cactus
[description] => description goes here..
[price] => $0.00
)
[1] => Array
(
[product_id] => 79
[name] => Product 4
[catname] => cactus
[description] => cactus goes here con..
[price] => $0.00
)
[2] => Array
(
[product_id] => 119
[name] => Product 1
[catname] => Special Sweets
[description] => This is a sweet
[price] => $0.00
)
[3] => Array
(
[product_id] => 59
[name] => Product 3
[catname] => Special Sweets
[description] => Corn goes here con..
[price] => $0.00
)
)