I have an associative array of arrays that I need to sort based on the number of elements in the child arrays. I'm doing this with usort, for example to sort utility categories by the number of service providers for each category:
<?php
$arr = array(
'Phone' => array(
'AT&T',
'Verizon',
'New Talk',
'Sage',
),
'Electricity' => array(
'Reliant',
),
'Television' => array(
'DIRECTV',
'Dish Network',
),
);
function utils_by_provider($a, $b) {
$a_sort = is_array($a) ? count($a) : 0;
$b_sort = is_array($b) ? count($b) : 0;
if ($a_sort == $b_sort) return 0;
return ($a_sort < $b_sort) ? -1 : 1;
}
usort($arr, 'utils_by_provider');
?>
The only issue is that, on the array it sorts, it also resets the keys to numeric incremental keys:
<?php
array(
0 => array(
'Reliant',
),
1 => array(
'DIRECTV',
'Dish Network',
),
2 => array(
'AT&T',
'Verizon',
'New Talk',
'Sage',
),
);
?>
How can I achieve the same sorting effect, but without destroying those keys?