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: [Chris] Sort Before Foreach Loop

By Perchpole - June 19, 2012

Hi, Chris -

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: [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