2016-02-05 115 views
1

我有一個簡單的多維數組,如下所示。我試圖計算陣列中每個值存在多少次(即關節炎=> 3)。我已經嘗試了所有不同的PHP函數,但它總是返回一個數字而不是一個key =>值對。我也看過類似的問題,但沒有什麼真正符合我的數組的簡單性。計算一個值出現在多維數組中的次數

array(3) { 
     [0]=> 
     array(1) { 
     [0]=> 
     string(0) "Arthritis" 
     } 
     [1]=> 
     array(4) { 
     [0]=> 
     string(7) "Thyroid" 
     [1]=> 
     string(10) " Arthritis" 
     [2]=> 
     string(11) " Autoimmune" 
     [3]=> 
     string(7) " Cancer" 
     } 
     [2]=> 
     array(6) { 
     [0]=> 
     string(7) "Anxiety" 
     [1]=> 
     string(10) " Arthritis" 
     [2]=> 
     string(11) " Autoimmune" 
     [3]=> 
     string(15) " Bone and Joint" 
     [4]=> 
     string(7) " Cancer" 
     [5]=> 
     string(8) " Candida" 
     } 

    } 

<?php 
print_r(count($items, COUNT_RECURSIVE)); 
?> 

回答

2

一種方法是把它壓扁成使用在子陣array_merge()一個維度,然後使用array_count_values()算值:

$count = array_count_values(call_user_func_array('array_merge', $items)); 
+0

謝謝,不知道它可以在一行中解決,非常感謝 – DEM

1

聽起來像是你需要一個定製的循環:

$counts = array(); 
foreach ($items as $item) { 
    foreach ($item as $disease) { // $disease here is the string like "Arthritis" 
     if (isset($counts[$disease])) // $disease then become the key for the resulting array 
      $counts[$disease]++; 
     else 
      $counts[$disease] = 1; 
    } 
} 
print_r($counts); 
+0

哇,這麼簡單,幾個小時的時間讓我的大腦癱瘓 - 你覺得你可以如何讓名字出現?謝謝一堆救了我。 – DEM

+0

@DEM我添加了一些可能有所幫助的評論。你也應該看看AbraCadaver的回答,我認爲他是最好的(也是最簡單的)。 – mopo922

+0

gotcha,感謝您的評論 - 看@ abraCadaver的,感謝您的幫助! – DEM

相關問題