I'm really stuck here. Im having an array looking like this below. And now I would like to count postStatus where postStatus = 0, for all of the arrays.
我真的被困在这里了。我有一个如下所示的阵列。现在我想计算postStatus,其中postStatus = 0,适用于所有数组。
So in this case there would be 2. But how do I do this?
所以在这种情况下会有2.但我该怎么做?
Array
(
[1] => Array
(
[postId] => 1
[postHeader] => Post-besked #1
[postContent] => Post content #1
[postDate] => 2011-12-27 17:33:11
[postStatus] => 0
)
[2] => Array
(
[postId] => 2
[postHeader] => Post-besked #2
[postContent] => POst content #2
[postDate] => 2011-12-27 17:33:36
[postStatus] => 0
)
)
3 个解决方案
#1
5
Just loop the outer array, check if there is a postStatus, increment a value to keep that count and you're done...
只需循环外部数组,检查是否有postStatus,增加一个值以保持计数,你就完成了......
$postStatus = 0;
foreach($myarray as $myarraycontent){
if(isset($myarraycontent['postStatus']) && $myarraycontent['postStatus'] == 0){
$postStatus++;
}
}
echo $postStatus;
EDIT:
编辑:
I forgot to mention that isset() can be used but a better pratice is to use array_key_exists because if $myarraycontent['postStatus'] is NULL, it will return false. Thats the way isset() works...
我忘了提到可以使用isset()但是更好的实践是使用array_key_exists,因为如果$ myarraycontent ['postStatus']为NULL,它将返回false。这就是isset()的工作原理......
#2
3
$count = count(
array_filter(
$array,
function ($item) {
return isset($item['postStatus']);
}
)
);
#3
1
How about this? Compact and concise :)
这个怎么样?小巧简洁:)
$postStatusCount = array_sum(array_map(
function($e) {
return array_key_exists('postStatus', $e) && $e['postStatus'] == 0 ? 1 : 0;
} , $arr)
);
#1
5
Just loop the outer array, check if there is a postStatus, increment a value to keep that count and you're done...
只需循环外部数组,检查是否有postStatus,增加一个值以保持计数,你就完成了......
$postStatus = 0;
foreach($myarray as $myarraycontent){
if(isset($myarraycontent['postStatus']) && $myarraycontent['postStatus'] == 0){
$postStatus++;
}
}
echo $postStatus;
EDIT:
编辑:
I forgot to mention that isset() can be used but a better pratice is to use array_key_exists because if $myarraycontent['postStatus'] is NULL, it will return false. Thats the way isset() works...
我忘了提到可以使用isset()但是更好的实践是使用array_key_exists,因为如果$ myarraycontent ['postStatus']为NULL,它将返回false。这就是isset()的工作原理......
#2
3
$count = count(
array_filter(
$array,
function ($item) {
return isset($item['postStatus']);
}
)
);
#3
1
How about this? Compact and concise :)
这个怎么样?小巧简洁:)
$postStatusCount = array_sum(array_map(
function($e) {
return array_key_exists('postStatus', $e) && $e['postStatus'] == 0 ? 1 : 0;
} , $arr)
);