Sorting multi-dimensional arrays in PHP
Last june I spotted a post about sorting multi-dimensional arrays in PHP. I immediately thought of a function I regularly use to deal with this and posted it in the comments. After I while I noticed that someone made a pastebin entry with the code, nicely naming me as the author.
Back in February 2011 I also received a nice “Thank you”, when I shared the snippet with someone on stackoverflow. So this little snippet must be useful to other people. Reason for me to finally put this on my blog:
<?php /* * Sort a multidimensional array on a column * * For example: * <code> * <?php array_qsort2($users, "username", "ASC"); ?> * </code> * * @param array $array array with hash array * @param mixed $column key that you want to sort on * @param enum $order asc or desc */ function array_qsort2 (&$array, $column=0, $order="ASC") { $oper = ($order == "ASC")?">":"<"; if(!is_array($array)) return; usort($array, create_function('$a,$b',"return (\$a['$column'] $oper \$b['$column']);")); reset($array); }
