0

有人可以帮助我吗?我正在尝试按内部数组的长度(降序)对二维数组进行排序。

这个数组:

Array
    (
      [0] => Array
        (
          [0] => "a"
        )

      [1] => Array
        (
          [0] => "a"
          [1] => "b"
          [2] => "c"
        )

      [2] => Array
        (
          [0] => "a"
          [1] => "b"
        )
    )

应该产生这个排序的数组:

Array
    (
      [0] => Array
        (
          [0] => "a"
          [1] => "b"
          [2] => "c"
        )

      [1] => Array
        (

          [0] => "a"
          [1] => "b"

        )

      [2] => Array
        (
          [0] => "a"

        )
    )

你有提示吗?

4

2 回答 2

1
// Comparison function
function cmp($a, $b) {
    $ca = count($a);
    $cb = count($b);
    if($ca == $cb)
        return 0;
    return ($ca < $cb ) ? -1 : 1;
}

// Sort the array
uasort($array, 'cmp');
于 2012-05-19T13:52:14.483 回答
0

是的,用于按元素usort排序。count()

<?php

header("Content-type: text/plain");

$array = array(
    array(
        "item1" => "key1",
        "item2" => "key2",
    ),
    array(
        "item1" => "key1",
        "item2" => "key2",
        "item3" => "key3"
    ),
    array(
        "item1" => "key1",
    )
);

usort($array, function($el1, $el2) {
    if (count($el1) === count($el2)) {
        return 0;
    }
    return count($el1) < count($el2) ? 1 : -1;
});

print_r($array);
于 2012-05-19T13:48:37.707 回答