计数特定值Occurence在一个阵列,PHP [英] Counting Occurence of Specific Value in An Array With PHP

查看:100
本文介绍了计数特定值Occurence在一个阵列,PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

乡亲。我试图找到一个本地的PHP函数,让我来数出数组中某个特定值出现的次数。我熟悉array_count_values​​()函数,而是返回所有值的计数在数组中。是否有一个功能,可以传递价值,只返回实例计数为特定值?例如:

  $阵列=阵列(1,2,3,3,3,4,4,5,6,6,6,6,7);$实例= some_native_function(6,$数组); // $实例将等于4

我知道如何crearte我自己的功能,但为什么要重新发明轮子?在此先感谢!


解决方案

 函数array_count_values​​_of(价值$,$阵列){
    $数= array_count_values​​($数组);
    返回$计数[$值];
}

不是的原始的,不过来了,这是很简单的。 ; - )

或者

 回声计数(array_filter($阵列功能($ N){返回$ N == 6;}));

或者

 回声array_reduce($阵列功能($ V,$ N){返回$ V +($ N == 6);},0);

或者

 回声计数(array_keys($阵列,6));

folks. I am trying to find a native PHP function that will allow me to count the number of occurences of a particular value in an array. I am familiar with the array_count_values() function, but that returns the count of all values in an array. Is there a function that allows you to pass the value and just return the instance count for that particular value? For example:

$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

I know how to crearte my own function, but why re-invent the wheel? Thanks in advance!

解决方案

function array_count_values_of($value, $array) {
    $counts = array_count_values($array);
    return $counts[$value];
}

Not native, but come on, it's simple enough. ;-)

Alternatively:

echo count(array_filter($array, function ($n) { return $n == 6; }));

Or:

echo array_reduce($array, function ($v, $n) { return $v + ($n == 6); }, 0);

Or:

echo count(array_keys($array, 6));

这篇关于计数特定值Occurence在一个阵列,PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆