计算每个值在数组中的存在次数(php)?

时间:2017-07-12 21:23:48

标签: php arrays

我试图输出每个值在数组中出现的总次数。这是我用来获取值的循环:

foreach( $EM_Bookings as $EM_Booking){              
    $types = $EM_Booking->get_person()->dbem_types;                     
}

以下是$types的var_dump,因此您可以看到我想要计算的数组:

string(2) "No" string(2) "No" string(3) "Yes" string(2) "No" string(2) "No" string(2) "No" string(14) "Not applicable" string(2) "No" string(2) "No"

我想输出每个唯一值的计数,如下所示:

  • 否= 7
  • 是= 1
  • 不适用= 1

我知道我需要使用array_count_values,但我不确定如何将它与我的foreach循环结合起来。我试过这样做:

$counts = array_count_values($types);

但显然这是不正确的。我是否需要以某种方式合并数组,然后计算它?我还在学习,所以我不太明白接下来我需要做什么。谢谢!

1 个答案:

答案 0 :(得分:1)

假设$types是一个字符串,这就是我如何跟踪一个值的使用次数。

$typeCounter =  array();
foreach ($EM_Bookings as $EM_Booking) {
    $types = $EM_Booking->get_person()->dbem_types;

    if (isset($typeCounter[$types]) === true) {
        $typeCounter[$types]++;
    } else {
        $typeCounter[$types] = 1;
    }
}

var_dump($typeCounter);

如果$types是一个字符串数组,代码将如下所示:

$typeCounter =  array();
foreach ($EM_Bookings as $EM_Booking) {
    $types = $EM_Booking->get_person()->dbem_types;

    foreach ($types as $type) {
        if (isset($typeCounter[$type]) === true) {
            $typeCounter[$type]++;
        } else {
            $typeCounter[$type] = 1
        }
    }
}

var_dump($typeCounter);