Created
April 14, 2015 10:40
-
-
Save josep11/863aa907ad70e87f2daa to your computer and use it in GitHub Desktop.
Sort associative array by attribute
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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