Skip to content

Instantly share code, notes, and snippets.

@dnavarrojr
Created December 3, 2018 18:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dnavarrojr/9f69b4a16c3596f8b7acf127ebf51317 to your computer and use it in GitHub Desktop.
Save dnavarrojr/9f69b4a16c3596f8b7acf127ebf51317 to your computer and use it in GitHub Desktop.
PHP Sort an Array of Arrays by Key
function array_sort_by_key( $array, $key ) {
$compare = make_key_cmp( $key );
usort( $array, $compare );
return $array;
}
function make_key_cmp( $key ) {
$code = "if (\$a['$key'] == \$b['$key']) return 0;";
$code .= "return (\$a['$key'] < \$b['$key']) ? -1 : 1;";
return create_function( '$a,$b', $code );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment