基于数组长度

时间:2016-11-18 11:54:34

标签: php arrays sorting multidimensional-array

PHP中基于数组长度排序数组数组的最佳方法是什么?

array (size=3)
   0 => 
      array (size=3)
         0 => string '1' (length=1)
         1 => string '2' (length=1)
         2 => string '3' (length=1)
   1 => 
      array (size=6)
         0 => string '1' (length=1)
         1 => string '2' (length=1)
         2 => string '3' (length=1)
         3 => string '4' (length=1)
         4 => string '5' (length=1)
         5 => string '6' (length=1)
   2 => 
      array (size=4)
         0 => string '1' (length=1)
         1 => string '2' (length=1)
         2 => string '3' (length=1)
         3 => string '4' (length=1)

我需要根据数组大小对其进行排序 变成这样:

array (size=3)
   0 => 
      array (size=6)
         0 => string '1' (length=1)
         1 => string '2' (length=1)
         2 => string '3' (length=1)
         3 => string '4' (length=1)
         4 => string '5' (length=1)
         5 => string '6' (length=1)
   1 =>     
      array (size=4)
         0 => string '1' (length=1)
         1 => string '2' (length=1)
         2 => string '3' (length=1)
         3 => string '4' (length=1)
   2 => 
      array (size=3)
         0 => string '1' (length=1)
         1 => string '2' (length=1)
         2 => string '3' (length=1)

有人可以帮我创建排序功能吗?谢谢

1 个答案:

答案 0 :(得分:3)

您应该使用usort

function cmp($a, $b){
    return (count($b) - count($a));
}
usort($array, 'cmp'); //$array is your array 
$arrayAfterSort = $array;