Skip to content

Instantly share code, notes, and snippets.

@josep11
Created April 14, 2015 10:40
Show Gist options
  • Save josep11/863aa907ad70e87f2daa to your computer and use it in GitHub Desktop.
Save josep11/863aa907ad70e87f2daa to your computer and use it in GitHub Desktop.
Sort associative array by attribute
/*
sortByAttribute($people, 'age'); //orders $people by age
$people = [
[
'name' => 'Josep',
'age' => '22'
],
[
'name' => 'Laura',
'age' => '54'
],
]
*/
public function sortByAttribute(&$arr, $attribute, $typeSort = SORT_DESC)
{
$num = []; //Array that is going to order the associative array $arr
foreach($arr as $key => $row)
{
$num[$key] = $row[$attribute];
}
array_multisort($num, $typeSort, $arr);
return $arr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment