Reputation: 5136
I have an array of products that I'm pulling from the db. I've verified that these are correct, using the following code:
$unsorted_products = products::get( array( 'collection' => $collection->id ) );
die(print_r($unsorted_products));
...and the results are as I expect. The thing is, I need the results to basically be grouped by a parent category and category. How they're sorted within each grouping, I don't care. Given that I don't have access to change the model that is retrieving the data via SQL, I need to sort this array via PHP. I'm using the following code:
$products = usort($unsorted_products, function ($a, $b) {
return strcmp(
$a->parentcategory.$a->categoryname,
$b->parentcategory.$b->categoryname
);
});
...but dumping the $products
array reveals that it is only holding the value 1. Any idea what I am doing wrong? I've verified that the properties I am attempting to access do exist in each object.
Thanks.
Upvotes: 0
Views: 84
Reputation: 319
You are doing it wrong. usort doesn't return array, it returns ether true or false. It changes array that you pass as first parameter.
After your code is executed, $unsorted_products becomes sorted array. Do this:
$products = products::get( array( 'collection' => $collection->id ) );
and this:
usort($products, function ($a, $b) {
return strcmp(
$a->parentcategory.$a->categoryname,
$b->parentcategory.$b->categoryname
);
});
Upvotes: 1
Reputation: 96266
It sorts the input array.
From the usort manual:
Returns TRUE on success or FALSE on failure.
Upvotes: 4