Reputation: 8312
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
)
)
Upvotes: 0
Views: 626
Reputation: 2017
You need to return $rrp
in your first one and return $name
in your second one, after your call to array_multisort
.
This is because the function is sorting the variables $rrp
and $name
, instead of the ones you originally passed to the function.
Edit: If you're simply trying to sort $products
by it's name
array value, a better method entirely is the following:
function sort_name($a,$b) {
return strcmp($a['name'],$b['name']);
}
$products = $cur_prod_cat["products"];
usort($products,'sort_name');
This uses the function sort_name
to 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.
Upvotes: 1