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

前端 未结 4 1086
忘了有多久
忘了有多久 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: <b>Notice</b>: Array to string conversion in <b>[...][...]</b>.

    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.

    0 讨论(0)
  • 2020-12-21 06:59

    This might be what you seek:

    natsort($sub_count);
    $rev = array_reverse($sub_count);
    $result = array_pad($rev, 3);
    

    You might want to omit the actual sorting if the values you have are already in order.

    0 讨论(0)
  • 2020-12-21 07:03

    You can achieve it by utilizing usort function.

    function cmp($a, $b){
        return (count($b) - count($a));
    }
    usort($array, 'cmp');
    $highest_3_sub_arrays = array_slice($array, 0, 3);
    
    0 讨论(0)
  • 2020-12-21 07:08
    $sizes=array();
    foreach ($myarray as $k=>$v) 
      if (!is_array($v)) $sizes["$k"]=0;
      else $sizes["$k"]=sizeof($v);
    
    sort($sizes);
    
    
    echo array_pop($sizes); //outputs 3
    echo array_pop($sizes); //outputs 2
    echo array_pop($sizes); //outputs 2
    
    0 讨论(0)
提交回复
热议问题