Skip to content

Instantly share code, notes, and snippets.

@Stichoza
Created November 26, 2012 10:51
Show Gist options
  • Save Stichoza/4147621 to your computer and use it in GitHub Desktop.
Save Stichoza/4147621 to your computer and use it in GitHub Desktop.
Sort 2D Arrays in PHP
<?php
/* Sort 2D Arrays
*
* Example:
* $user_array = Array(
* Array("id" => 521, "name" => "Aboriginal Anemia"),
* Array("id" => 281, "name" => "Chemical Crap"),
* Array("id" => 596, "name" => "Bloody Baphomet")
* );
* $sorted_user_array = array_sort_2d($user_array, "name", "DESC");
*/
function array_sort_2d($array, $sortby, $direction='ASC') {
$sort_arr = array();
$temp_arr = array();
foreach ($array as $k => $v) {
$temp_arr[] = strtolower($v[$sortby]);
}
if ($direction=='ASC') {
asort($temp_arr);
} else {
arsort($temp_arr);
}
foreach ($temp_arr as $k=>$tmp) {
$sort_arr[] = $array[$k];
}
return $sort_arr;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment