Skip to content

Instantly share code, notes, and snippets.

@pranid
Created March 24, 2020 16:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pranid/99ed79676952f81d1c28f6f530295bc0 to your computer and use it in GitHub Desktop.
Save pranid/99ed79676952f81d1c28f6f530295bc0 to your computer and use it in GitHub Desktop.
PHP - Multidimensional array sorting by specific key
<?php
/**
* @param array $array
* @param string $_key
* @param string $_direction
* @version 1.0.0
* @author Praneeth Nidarshan (praneeth.nidarshan@gmail.com)
*/
function multiArraySort(&$array, $_key,$_direction = 'desc')
{
usort($array, function ($a, $b) use ($_key, $_direction) {
$a = $a["{$_key}"];
$b = $b["{$_key}"];
if ($a == $b) {
return 0;
}
if ($_direction == 'desc') {
return ($a < $b) ? 1 : -1;
} else {
return ($a < $b) ? -1 : 1;
}
});
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment