首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >用PHP统计数组中特定值的出现次数

用PHP统计数组中特定值的出现次数
EN

Stack Overflow用户
提问于 2011-05-10 12:36:05
回答 5查看 47.4K关注 0票数 26

我正在尝试寻找一个原生PHP函数,它允许我计算数组中特定值出现的次数。我熟悉array_count_values()函数,但它返回数组中所有值的计数。是否有一个函数允许您传递该值并只返回该特定值的实例计数?例如:

$array = array(1, 2, 3, 3, 3, 4, 4, 5, 6, 6, 6, 6, 7);

$instances = some_native_function(6, $array);  //$instances will be equal to 4

我知道如何创建自己的函数,但为什么要重新发明轮子呢?

EN

回答 5

Stack Overflow用户

发布于 2011-05-10 12:43:48

此解决方案可能接近您的要求

$array = array(1, 2, 3, 3, 3, 4, 4, 5, 6, 6, 6, 6, 7);
print_r(array_count_values($array));

Result:

Array
( [1] => 1 ,[2] => 1 , [3] => 3, [4] => 2,[5] =>1, [6] => 4, [7] => 1 )

为了details

票数 13
EN

Stack Overflow用户

发布于 2015-07-02 02:39:00

从PHP5.4.0开始,您可以对由array_count_values()生成的数组的索引[6]使用函数数组取消引用

$instances = array_count_values($array)[6];

因此,如果找不到,则检查并分配0

$instances = array_count_values($array)[6] ?? 0;
票数 12
EN

Stack Overflow用户

发布于 2014-10-24 10:55:11

假设我们有以下数组:

     $stockonhand = array( "large green", "small blue", "xlarge brown", "large green", "medieum yellow", "xlarge brown",  "large green");

1)将此函数复制并粘贴到页面顶部。

    function arraycount($array, $value){
    $counter = 0;
    foreach($array as $thisvalue) /*go through every value in the array*/
     {
           if($thisvalue === $value){ /*if this one value of the array is equal to the value we are checking*/
           $counter++; /*increase the count by 1*/
           }
     }
     return $counter;
     }

2)接下来需要做的就是在每次要计算任何数组中的任何特定值时都应用该函数。例如:

     echo arraycount($stockonhand, "large green"); /*will return 3*/

     echo arraycount($stockonhand, "xlarge brown"); /*will return 2*/
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5945199

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档