2012-02-26 59 views
2

大小的多維數組我有這樣的多維數組:排序由其子陣

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 
     ) 

當我算子陣我得到這個1,2,2,3。我怎麼能在3,2,2,1收到它?我需要得到例如最後3個子陣列的最高子陣列數(DESC,這意味着3,2,2)。我怎樣才能做到這一點?

+0

這麼多重複的相關部分 - > – 2012-02-26 18:14:37

回答

6

您可以通過使用usort函數來實現它。

function cmp($a, $b){ 
    return (count($b) - count($a)); 
} 
usort($array, 'cmp'); 
$highest_3_sub_arrays = array_slice($array, 0, 3); 
+0

感謝您提供優秀的解決方案! – peter 2012-02-26 18:49:00

3

這可能是你所追求的:

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

你可能想省略實際排序,如果你有值已經在秩序。

+0

非常好,簡單的解決方案! – 2012-02-26 17:58:33

1
$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

謝謝,它也可以。只需將回顯重命名爲: print_r(array_pop($ sizes)); //輸出3 print_r(array_pop($ sizes)); //輸出2 print_r(array_pop($ sizes)); //輸出2 – peter 2012-02-26 18:50:54

0

在我看來,所有其他的答案是工作太辛苦。 usort(),count()foreach()沒有必要,當我試着natsort()它給了我:<b>Notice</b>: Array to string conversion in <b>[...][...]</b>

rsort()將首先放置最長的子陣列。

代碼:

$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 

輸出:

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', 
), 
) 

如果你想實現一些額外的排序打破長度的關係(如您的兩個2元子陣列),那麼你會需要在你的問題中指定。