[英]How to count elements inside array/object on PHP?
I have this array being sent to my view我有这个数组被发送到我的视图
Array
(
[0] => stdClass Object
(
[emg_id] => 2
[fkit] => 1
[door] =>
)
)
I would like to count how many elements are empty, NULL, or '0'.我想计算有多少元素是空的,NULL 或“0”。
I tried using count
but it always returns '1', instead of counting all of the elements, so I can later determine which satisfy my conditions above.我尝试使用
count
,但它总是返回'1',而不是计算所有元素,所以我以后可以确定哪些满足我的上述条件。
Any ideas what I'm doing wrong?任何想法我做错了什么?
// number of "null" elements
echo count(array_filter((array) $array[0], 'is_null'));
There are some other is_*()
-functions built-in, that may help you for example to count the number of strings (and so on).还有一些其他
is_*()
内置函数,例如可以帮助您计算字符串的数量(等等)。
To test, if an element is (eg) 0
, I suggest to use an anonymous function为了测试,如果一个元素是(例如)
0
,我建议使用匿名 function
echo count(array_filter((array) $array[0], function ($item) {
return $item === 0;
}));
The other cases are similar.其他情况类似。
loop through them and count.遍历它们并计数。
function loopMe($array, $value) {
$num = 0;
foreach($array as $key=>$val) {
if($val == $value)
$num++;
}
return $num;
}
$ar = array (
array (
"emg_id" => 2
"fkit" => 1
"door" => null));
$num = loopMe($ar[0], null);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.