2012-03-19 35 views
1

我有一個多維數組:多維數組:如何建立一個遞歸數()

membership = array(5) { 
[0]=> array(4) { [0]=> string(21) "Group A" [1]=> string(9) "10/1/2011" [2]=> string(9) "3/31/2012" [3]=> string(8) "00004130" } 
[1]=> array(4) { [0]=> string(22) "Group B" [1]=> string(8) "4/1/2011" [2]=> string(9) "9/30/2011" [3]=> string(8) "00005005" } 
[2]=> array(4) { [0]=> string(22) "Group A" [1]=> string(9) "10/1/2010" [2]=> string(9) "3/31/2011" [3]=> string(8) "00004130" } 
[3]=> array(4) { [0]=> string(22) "Group B" [1]=> string(8) "4/1/2010" [2]=> string(9) "9/30/2010" [3]=> string(8) "00005005" } 
[4]=> array(4) { [0]=> string(22) "Group B" [1]=> string(8) "10/1/2010" [2]=> string(9) "3/31/2011" [3]=> string(8) "00005005" } 
} 

我需要發現哪一組成員陣列中出現了多少次。

PHP的計數()沒有遞歸功能,但它是如果它沒有輸出將是理想的(即,[ '組A'] => 2 [ 'B組'] => 3)。

我想過使用array_diff_uassoc()但我只是不確定。所以我覺得在我漫無目的地走錯路之前尋求一些幫助是明智的。我確信有不止一種方法,但我總是在SO上找到非常有趣的編碼概念。

我正在運行php 5.3.5預先感謝您的建議和幫助。

+3

'PHP的計數()沒有遞歸capability'吧?查看'count's'第二個參數的手冊。無論如何,它不會做你想要的東西,只需簡單地使用'foreach'就是這樣。 – 2012-03-19 05:35:15

+0

數據來自db嗎? – 2012-03-19 05:35:34

+1

因爲它們都處於相同的深度,爲什麼你需要遞歸?潛在的未來重用? – Rick 2012-03-19 05:38:03

回答

2

這應該做的伎倆用最少的代碼:

$memberships = array(); // Your multi-dimensional array 

foreach($memberships as $membership) 
{ 
    $count[$membership[0]]++; 
} 

var_dump($count) 

對不起,我遲到後BTW,我想test it,使肯定它會按預期工作。

輸出是:

array(2) { 
    ["Group A"]=> 
    int(2) 
    ["Group B"]=> 
    int(3) 
} 
+0

謝謝!漂亮,乾淨,簡單。感謝您抽出寶貴的時間! – Ricalsin 2012-03-19 06:27:11

+0

並感謝Ideone.com的測試結果!我看過這個網站在我的搜索中會更多。它看起來很有趣。謝謝。 – Ricalsin 2012-03-19 14:13:41

+0

是的,我最近纔開始使用它。測試小代碼片段以確保解決方案實際工作非常方便。 – 2012-03-19 22:44:35

1

給出你有什麼,就是這樣。甚至不需要是遞歸的,因爲你的數組只是2D

<?php 
$membership = array( 
    array("Group A","10/1/2011","3/31/2012","00004130"), 
    array("Group B","4/1/2011","9/30/2011","00005005"), 
    array("Group A","10/1/2010","3/31/2011","00004130"), 
    array("Group B","4/1/2010","9/30/2010","00005005"), 
    array("Group B","10/1/2010","3/31/2011","00005005") 
); 

//initialize array for safety 
$count = array(); 

//loop through each item 
foreach($membership as $row){ 

    //check if group exists in count array 
    $group = $row[0]; 
    $groupExists = array_key_exists($group,$count); 

    if($groupExists){ 
     //if we've crossed paths before, just add 1 
     $count[$group]++; 
    } else { 
     //otherwise, let's start with 1 
     $count[$group]=1; 
    } 
} 

var_dump($count); 

//output dump should look like 
array(2) { 
    ["Group A"]=> int(2) 
    ["Group B"]=> int(3) 
} 
+0

感謝您抽出時間,約瑟夫。 Cillosis只是更簡單,但我很欣賞你的帖子中的教訓。再次謝謝你! – Ricalsin 2012-03-19 06:28:57