I have an array such as:
Array
(
[DEF] => Array
(
[0] => Array
(
[type] => 1
Using uksort:
uksort($array, function($a, $b) { return count($b) - count($a); });
Using array_multisort
:
array_multisort(array_map('count', $array), SORT_DESC, $array);
With PHP < 5.3:
function sort_cb($a, $b) {
return count($b) - count($a);
}
uksort($array, 'sort_cb');
$tempArr = $sortedArr = array();
foreach ($myArr as $k => $v) $tempArr[$k] = count($v);
asort($tempArr);
foreach ($tempArr as $k => $v) $sortedArr = $myArr[$k];
Note that this will break if any of the array values are not themselves arrays, you may want to add an is_array()
check somewhere...
<?php
function cmp($a, $b)
{
if ($a == $b) {
return 0;
}
return (count($a) > count($b)) ? -1 : 1;
}
$a = array(
"AA" => array(
array('type'=>'1', 'id'=>'2'),
array('type'=>'2', 'id'=>'2')),
'BB' => array(
array('type'=>'1', 'id'=>'2'),
array('type'=>'2', 'id'=>'2'),
array('type'=>'5', 'id'=>'2')),
'CC' => array(
array('type'=>'1', 'id'=>'2'))
);
usort($a, "cmp");
print_r($a);
?>