繁体   English   中英

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

[英]Count the number of times a value appears in a multi-dimensional array

我有一个简单的多维数组,如下所示。 我试图计算阵列中每个值存在多少次(即关节炎=> 3)。 我已经尝试了所有不同计数的PHP函数,但它总是返回一个数字,而不是一个键=>值对。 我也在寻找类似的问题,但没有什么真正适合我的数组的简单性。

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

听起来你需要一个自定义循环:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM