Sort a multi-dimensional array by the size of its

2019-01-28 19:47发布

问题:

I have this multidimensional array:

Array
(
    [0] => Array
        (
        [0] => 2012-02-26 07:15:00
        )
    [1] => Array
        (
            [0] => 2012-02-26 17:45:00
            [1] => 2012-02-26 18:55:00
        )
    [2] => Array
        (
            [0] => 2012-02-26 18:55:00
            [1] => 2012-02-26 17:45:00
        )
    [3] => Array
        (
            [0] => 2012-02-26 18:57:00
            [1] => 2012-02-26 17:45:00
            [2] => 2012-02-26 18:55:00
        )

When I count subarrays I get this 1,2,2,3. How could I receive it in 3,2,2,1? I need to get for example last 3 subarrays with the highest subarray count (DESC, it means 3,2,2). How can I achieve this?

回答1:

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


回答2:

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.



回答3:

$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


回答4:

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.