简体   繁体   中英

How to sort a two-dimensional array by length of inner arrays in PHP?

Can somebody help me? I'm trying to sort an two dimensional array by the length of the inner arrays (descending).

This array:

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

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

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

should result in this sorted array:

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

      [1] => Array
        (

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

        )

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

        )
    )

Do you have a hint?

// 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');

Yes, use usort to sort by the count() of the elements.

<?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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM