Sort array based on the number of elements in the secondary array set as the value in PHP

StackOverflow https://stackoverflow.com/questions/21199927

  •  29-09-2022
  •  | 
  •  

I gave an array populated to look like this -

$array = array(
   0 => array(2,3,4),
   1 => array(2,3,7,6,8),
   -- and so on  
 );

Is there a shorthand in PHP/PHP5.x to accomplish sorting of such an array based on the number of elements in the value to each key of the primary array? Thanks.

有帮助吗?

解决方案

Use usort()

function cmp($a, $b) {
    if (count($a) == count($b)) {
        return 0;
    }
    return (count($a) < count($b)) ? -1 : 1;
}

usort($array, "cmp");

Here's a better optimized version of that function (only calling count() twice):

function cmp($a, $b) {
    $numA = count($a);
    $numB = count($b)
    if ($numA == $numB) {
        return 0;
    }
    return ($numA < $numB) ? -1 : 1;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top