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