Reputation: 10288
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');
)
Upvotes: 2
Views: 260
Reputation: 454980
You can do this in 2 steps.
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;
}
Upvotes: 1
Reputation: 32912
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
Upvotes: 2
Reputation: 8910
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()
.
Upvotes: 4