News:

Wondering if this will always be free?  See why free is better.

Main Menu

Best way to sort a multi-dimensional array?

Started by nend, March 10, 2016, 12:20:44 AM

Previous topic - Next topic

nend

Ok, I have a array I need sorted by two keys. I know two ways of sorting it and both work perfectly. Just wondering what is the best way or if there is another better method.

Here we are going through the array, then using array_multisort.

foreach ($context['post_boards'] as $key => $ddata) {
$dcat[$key]  = $ddata['cat']['name'];
$dboard[$key] = $ddata['name'];
}
array_multisort($dcat, SORT_ASC, $dboard, SORT_ASC, $context['post_boards']);

Here we are using usort with a function created on the fly to compare the data.

usort($context['post_boards'], create_function('$a,$b','return strcmp($a["cat"]["name"].$a["name"], $b["cat"]["name"].$b["name"]);'));

live627

* live627 looks up array_multisort, but only got confused

Usually the PHP manual doesn't fail so epically on me...

nend

Quote from: live627 on March 10, 2016, 06:23:23 PM
* live627 looks up array_multisort, but only got confused

Usually the PHP manual doesn't fail so epically on me...

The $key is what you want sorted, the var is the string you want it sorted by.

So first I am sorting by categories then sorting the boards within them.  ;)

Advertisement: