Looking at the answers to this question: PHP array multiple sort - by value then by key?, it seems array_multisort
is the way to go. (I'm not really sure how array_multisort
works, I just kinda hacked this up, and it seems to work).
Try this:
$arr = array(
'foo bar' => 6,
'foo' => 10,
'bar' => 6,
'b' => 5,
'foo bar bar bar foo' => 6,
'foo bar bar foo' => 10
);
array_multisort(array_values($arr), SORT_DESC,
array_map(create_function('$v', 'return strlen($v);'), array_keys($arr)),
SORT_DESC, $arr);
Demo: http://codepad.org/mAttNIV7
UPDATE: Added array_map
to make it sort by the length of the string, before it was just doing:
$str1 > $str2
instead of strlen($str1) > strlen($str2)
.
UPDATE 2: In PHP >= 5.3, you can replace create_function
with a real anonymous function.
array_map(function($v){return strlen($v);}, array_keys($arr))
Demo 2: http://codepad.viper-7.com/6qrFwj