'Is there an alternative to uasort which can sort by key?
I am building something very flexible which doesn't know what it will sort. It's part of a REDIS thing I'm working on. Anyway, I need to sort an array of arrays by a user-defined key. So this:
var $sortme=Array(
"a"=>array("name"=>"john","yearofbirth"=>2000),
"b"=>array("name"=>"andre","yearofbirth"=>1994))
I would like to sort this by 'name' or 'yearofbirth'. To sort by name I use this:
uasort($sortme,function($a,$b){return strcmp($a["name"],$b["name"]);}
But I like to be able to sort by any key, to make things as flexible as possible. My first attempt was this, but that didn't work:
$sortby="name";
uasort($sortme,function($a,$b){return strcmp($a[$sortby],$b[$sortby]);}
The reason it didn't work is that $sortby is not know within the sort function. I could define a global var for it, but that solution is just too horrible.
Any ideas?
Solution 1:[1]
There is another way to use it. ref
$data = array(
array("firstname" => "Mary", "lastname" => "Johnson", "age" => 25),
array("firstname" => "Amanda", "lastname" => "Miller", "age" => 18),
array("firstname" => "James", "lastname" => "Brown", "age" => 31),
array("firstname" => "Patricia", "lastname" => "Williams", "age" => 7),
array("firstname" => "Michael", "lastname" => "Davis", "age" => 43),
array("firstname" => "Sarah", "lastname" => "Miller", "age" => 24),
array("firstname" => "Patrick", "lastname" => "Miller", "age" => 27)
);
array_multisort (array_column($data, 'firstname'), SORT_ASC, $data);
var_dump($data);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | codediesel |
