Good morning, I'm just shook about it but, php has more than 10 ways to sort an array but I can't find one to sort by desired key dynamically.
I cannot set something like some uksorts because it will be filled dynamically. I'm using smarty on the front (which does not have array sort functions) and I'm trying to make a callable static to resort and print sorted arrays on one specific point.
I've applied some logic on it and I think it would be something like this.
Smarty:
{assign var='key' value='category_id'}
{assign var='direction' value='normal'}
{assign var='sortedItem' value=''}
{foreach $object.prop item="item"}
{sortedItem = Class::arraySortBy($item, $key, $direction)}
<a href="{$item['link']}">
{$item['name']}
</a>
{foreach}
PHP:
public static function arraySortBy($elemGroup, $sortBy, $direction) {
if(is_object($elemGroup)){
$elemGroup = (array) $elemGroup;
}
if ($direction == 'normal') {
// here is where i want to sort the elemGroup array by the key i want, as the key is product_id and i want to sort by category_id
} else if ($direction == 'reverse'){
// here the same but in reverse order
} else {
error_log('Direction not properly set.');
}
return $elemGroup;
}
the fact is that i want to re-order the objects bu category_id, and second by product_id IE:
itemA{product_id=1, category_id=1}
itemB{product_id=2, category_id=2}
itemC{product_id=3, category_id=1}
itemE{product_id=4, category_id=1}
itemD{product_id=5, category_id=2}
Result:
itemA
itemB
itemC
itemE
itemD
expected result
itemA
itemC
itemE
itemB
itemD
Is there a way to make this with PHP sorting functions or it has to be custom?
Thanks