Sort a multi-dimensional array by the size of its sub-arrays

前端 未结 4 1099
忘了有多久
忘了有多久 2020-12-21 06:40

I have this multidimensional array:

Array
(
    [0] => Array
        (
        [0] => 2012-02-26 07:15:00
        )
    [1] => Array
        (
              


        
4条回答
  •  南方客
    南方客 (楼主)
    2020-12-21 06:56

    It seems to me that all of the other answers are working too hard. usort(), count(), and foreach() aren't necessary and when I tried natsort() it gave me: Notice: Array to string conversion in [...][...].

    rsort() will put the longest subarrays first.

    Code:

    $array=array(
        ["2012-02-26 18:55:00","2012-02-26 17:45:00"],
        ["2012-02-26 07:15:00"],
        ["2012-02-26 18:57:00","2012-02-26 17:45:00","2012-02-26 18:55:00"],
        ["2012-02-26 17:45:00","2012-02-26 18:55:00"]
    );
    
    $size=3; // modify this line to declare how many subarrays to capture
    rsort($array); // sort the subarrays in DESC order
    var_export(array_slice($array,0,$size));  // print the first n subarrays
    

    Output:

    array (
      0 => 
      array (
        0 => '2012-02-26 18:57:00',
        1 => '2012-02-26 17:45:00',
        2 => '2012-02-26 18:55:00',
      ),
      1 => 
      array (
        0 => '2012-02-26 18:55:00',
        1 => '2012-02-26 17:45:00',
      ),
      2 => 
      array (
        0 => '2012-02-26 17:45:00',
        1 => '2012-02-26 18:55:00',
      ),
    )
    

    If you want to implement some additional sorting to break the length-ties (like between your two 2-element subarrays), then you will need to specify that in your question.

提交回复
热议问题