Sort Before Foreach Loop
5 posts by 2 authors in: Forums > CMS Builder
Last Post: June 19, 2012 (RSS)
By Perchpole - June 19, 2012
I just wondered what was the best course of action for sorting a getCategories() call before executing a foreach loop?
I need to output the results into alphabetical order using the $category['name'].
Any help would be most welcome.
:0)
Perch
Re: [Perchpole] Sort Before Foreach Loop
By Chris - June 19, 2012
Assuming that you simply want to sort the records as a list (and not sort within each branch of the category tree,) my favourite way to sort records would be with array_multisort() and array_pluck():
array_multisort(
array_pluck($records, 'name'), SORT_ASC,
$records
);
That will sort the array in-place, so that when you foreach, they'll be in the right order.
Hope that helps!
Chris
Re: [Chris] Sort Before Foreach Loop
By Perchpole - June 19, 2012
I thought array_multisort would come into the reckoning somewhere!
Tell me, I see array_pluck mentioned from time to time on this forum - but I still don't fully understand what it does.
Could you explain it please.
:0)
Perch
Re: [Perchpole] Sort Before Foreach Loop
By Chris - June 19, 2012
pluck() exists in a few languages and frameworks. I think I first ran into it in the fantastic Underscore.js library. It collects one field from a list of records into a new array. It's essentially a short-hand for this:
$values = array();
foreach ($array as $record) {
$values[] = $record['key'];
}
showme($values);
With array_pluck, that can be written as:
showme(array_pluck($array, 'key'));
Hope that makes sense!
Chris
Re: [Chris] Sort Before Foreach Loop
By Perchpole - June 19, 2012
That's a really useful bit of shorthand.
Thanks,
:0)
Perch