Neither of these work… (nothing is sorted)
I adapted these from an example on the PHP docs site.
class ProductHelper {
function sortProductsByPrice($products, $sort = SORT_ASC) {
foreach ($products as $key => $row) {
$name[$key] = $row['name'];
$rrp[$key] = $row['rrp'];
}
array_multisort($rrp, $sort, $name, SORT_ASC, $products);
}
function sortProductsByName($products, $sort = SORT_ASC) {
foreach ($products as $key => $row) {
$name[$key] = $row['name'];
}
array_multisort($name, $sort, $products);
}
}
This is how i’m using it:
$products = $cur_prod_cat["products"]; // copy an array of products
$PRODUCT_HELPER->sortProductsByName($products); //sort it
In case you need to see, the products array looks something like this:
Array (
[0] => Array (
[id] => 0
[name] => product name
[description] => product description
[price] => product price
[etc] => other attributes
)
[1] => Array (
[id] => 1
[name] => product name
[description] => product description
[price] => product price
[etc] => other attributes
)
)
You need to
return $rrpin your first one andreturn $namein your second one, after your call toarray_multisort.This is because the function is sorting the variables
$rrpand$name, instead of the ones you originally passed to the function.Edit: If you’re simply trying to sort
$productsby it’snamearray value, a better method entirely is the following:This uses the function
sort_nameto determine which element in the array to put first.You can then create more
sort_{value}functions if you desire, and just change the field value it contains.