简体   繁体   中英

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

I have a simple multi-dimensional array that looks like below. I am trying to count how many times each value exists in the array (ie arthritis => 3). I have tried all the different count PHP functions but it always returns a number and not a key => value pair. I have also looked on SO for similar questions, but nothing really fits the simplicity of my array.

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

Sounds like you need a custom loop:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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