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