<?php /** * sort_multi_array * * Sort a two-dimensional array by one (or more) of the elements in the nested arrays. Accepts a variable number of arguments. * * @version 0.1 * @author Contributors at eXorithm * @link /algorithm/view/sort_multi_array Listing at eXorithm * @link /algorithm/history/sort_multi_array History at eXorithm * @license /home/show/license * * @param array $array Two dimensional array. Each array in the array should have the same keys. * @param mixed $key Key in the sub-arrays to sort by. * @return array */ function sort_multi_array($array=array(0=>array('surname'=>'Smith','givenname'=>'Henrietta'),1=>array('surname'=>'Smythe','givenname'=>'Stuart'),2=>array('surname'=>'Black','givenname'=>'Conrad'),3=>array('surname'=>'Smith','givenname'=>'Abigail'),4=>array('surname'=>'Eaves','givenname'=>'Ruth'),5=>array('surname'=>'Travis','givenname'=>'Earl')),$key='surname') { $keys = array(); for ($i=1;$i<func_num_args();$i++) { $keys[$i-1] = func_get_arg($i); } // create a custom search function to pass to usort $func = function ($a, $b) use ($keys) { for ($i=0;$i<count($keys);$i++) { if ($a[$keys[$i]] != $b[$keys[$i]]) { return ($a[$keys[$i]] < $b[$keys[$i]]) ? -1 : 1; } } return 0; }; usort($array, $func); return $array; } ?>