2

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');
)
1
  • Are you looking for elegant or "good enough"? Commented Oct 28, 2010 at 6:31

3 Answers 3

4

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().

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.