计算一个值出现在多维数组中的次数

问题描述:

我有一个简单的多维数组,如下所示。我试图计算阵列中每个值存在多少次(即关节炎=> 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)); 
?> 

一种方法是把它压扁成使用在子阵array_merge()一个维度,然后使用array_count_values()算值:

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

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

听起来像是你需要一个定制的循环:

$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