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?
1 Answer