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