views:

45

answers:

3

I would like to be able to sort this array by the element array's size;

array( 
    [0] =>  array( [0] => 'B',  [1] => 'C');
    [1] =>  array( [0] => 'B');
    [2] =>  array( [0] => 'A', [1] =>  'C');
    [3] =>  array( [0] => 'A', [1] =>  'B', [2] =>  'C');
    [4] =>  array( [0] => 'C');       
    [5] =>  array( [0] => 'A');
    [6] =>  array( [0] => 'A', [1] =>  'B');
   )


array( 
    [0] =>  array( [0] => 'A');
    [1] =>  array( [0] => 'B');
    [2] =>  array( [0] => 'C');
    [3] =>  array( [0] => 'A', [1] =>  'B');
    [4] =>  array( [0] => 'A', [1] =>  'C');
    [5] =>  array( [0] => 'B',  [1] => 'C');
    [6] =>  array( [0] => 'A', [1] =>  'B', [2] =>  'C');
)
+5  A: 

Using closures (PHP 5.3):

usort($array, function($a, $b) { return count($a) - count($b); });

Without using closures (PHP 5.2):

usort($array, create_function('$a, $b', 'return count($a) - count($b)'));

Note that $array will be sorted in place. Don't look for it in the return value of usort().

kijin
+2  A: 

I have not tested this, but I hope you can get the point.

function yoursort($a,$b) {
  if(!(is_array($a) && is_array($b)) return 0; // item of array is not an array
  $cntA = sizeof($a);
  $cntB = sizeof($b);
  if($cntA!=$cntB) return $cntA-$cntB; // smaller array up
  foreach($a as $key=>$val) {
    $ordA = ord($a[$key]);
    $ordB = ord($b[$key]);
    if($ordA!=$ordB) return $ordA-$ordB; // sort sub array by alphabet
  }
  return 0; // items are equal
}
usort($yourarray,"yoursourt");

Here you can find more about usort http://php.net/manual/en/function.usort.php

Jan Turoň
A: 

You can do this in 2 steps.

  • In step 1, sort individual arrays on value.
  • In step 2, sort the 2D array, first based on size and if the size are not equal sort on the values.

Code:

foreach($input as $key => $val) {
        sort($input[$key]);
}
usort($input, "cmp");
print_r($input);

function cmp($a,$b) {
        if(count($a) != count($b)) {
                return count($a) - count($b);
        }
        for($i=0;$i<count($a);$i++) {
                if($a[$i] != $b[$i]) {
                        return strcmp($a[$i],$b[$i]);
                }
        }
        return 0;
}

Code in Action

codaddict