Sort Before Foreach Loop

5 posts by 2 authors in: Forums > CMS Builder
Last Post: June 19, 2012   (RSS)

By Perchpole - June 19, 2012

Hello, All -

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

Hi Perch,

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!
All the best,
Chris

Re: [Perchpole] Sort Before Foreach Loop

By Chris - June 19, 2012

Hi Perch,

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!
All the best,
Chris

Re: [Chris] Sort Before Foreach Loop

By Perchpole - June 19, 2012

Ah. Now I understand.

That's a really useful bit of shorthand.

Thanks,

:0)

Perch