问题描述
我有一个关联数组,我需要在其中计算布尔真值的数量.
I have an associative array in which I need to count the number of boolean true values within.
最终结果是创建一个 if 语句,当数组中只存在一个真值时,该语句将返回真值.如果数组中有多个真值,或者数组中没有真值,则需要返回 false.
The end result is to create an if statement in which would return true when only one true value exists within the array. It would need to return false if there are more then one true values within the array, or if there are no true values within the array.
我知道最好的方法是以某种形式使用 count 和 in_array .我不确定这是否可行,只是在我的头顶上,但即使可行,这是最好的方法吗?
I know the best route would be to use count and in_array in some form. I'm not sure this would work, just off the top of my head but even if it does, is this the best way?
$array(a->true,b->false,c->true)
if (count(in_array(true,$array,true)) == 1)
{
return true
}
else
{
return false
}
推荐答案
我会使用 array_filter.
I would use array_filter.
$array = array(true, true, false, false);
echo count(array_filter($array));
//outputs: 2
http://codepad.viper-7.com/ntmPVY
Array_filter 将删除 false-y (value == false) 的值.那就来数一数吧.如果您需要根据某些特殊值进行过滤,例如您正在查找特定值,则 array_filter 接受一个可选的第二个参数,该参数是您可以定义的函数,用于返回值是 true(未过滤)还是 false(过滤掉)).
Array_filter will remove values that are false-y (value == false). Then just get a count. If you need to filter based on some special value, like if you are looking for a specific value, array_filter accepts an optional second parameter that is a function you can define to return whether a value is true (not filtered) or false (filtered out).
这篇关于PHP Count 布尔数组中真值的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)