PHP按子数量排序子数组,然后按子数组键排序

时间:2014-07-03 11:04:45

标签: php arrays sorting

对多维数组进行排序的最简单方法是什么。我需要对它进行排序,以便输出显示在子数组上的最大值数,然后按子数组的键按字母顺序排序:

这样的事情:

MyArray(
  subarray4('val1')
  subarray2('val1')
  subarray3('val1', 'val2', 'val3')
  subarray1('val1', 'val2', 'val3')
)

看起来更像是这样:

MyArray(
  subarray1('val1', 'val2', 'val3')
  subarray3('val1', 'val2', 'val3')
  subarray2('val1')
  subarray4('val1')
)

2 个答案:

答案 0 :(得分:0)

$array = array(
    array('val1'),
    array('val1'),
    array('val1', 'val2', 'val3'),
    array('val1', 'val2', 'val3'),
);

function sortByCount($a, $b) {
    $a = count($a);
    $b = count($b);

    if($a == $b) {
        return 0;
    }

    return ($a > $b) ? -1 : 1;
}

uasort($array, 'sortByCount');

答案 1 :(得分:0)

这里有两个步骤,首先根据子阵列计数对数组进行排序,然后通过数组对每个子阵列进行“字母数字”排序。

$myArray = array(
  array('val1', 'val2'),
  array('val3'),
  array('val7', 'val6', 'val5', 'val4'),
  array('val8', 'val9', 'val10'),
);

// sort primary array by subarray count
uasort($myArray, function ($a, $b) {
    $a = count($a);
    $b = count($b);
    return ($a == $b) ? 0 : (($a > $b) ? -1 : 1);
});

// now sort each subarray alphanumerically
foreach ( $myArray as $key => $arr ) {
    natsort($myArray[$key]); // letters - alpha, numbers - numeric
    // note: ignoring $arr because sorting it does not affect $myArray
}

print '<pre>';
print_r($myArray);
print '</pre>';

输出:

Array
(
    [2] => Array
        (
            [3] => val4
            [2] => val5
            [1] => val6
            [0] => val7
        )

    [3] => Array
        (
            [0] => val8
            [1] => val9
            [2] => val10
        )

    [0] => Array
        (
            [0] => val1
            [1] => val2
        )

    [1] => Array
        (
            [0] => val3
        )

)

uasort排序算法从此处剪切并粘贴:Sorting array by count of subarray