如何在 PHP 数组中递归运行 array_filter? [英] How to run array_filter recursively in a PHP array?
问题描述
给定以下数组 $mm
Array
(
[147] => Array
(
[pts_m] =>
[pts_mreg] => 1
[pts_cg] => 1
)
[158] => Array
(
[pts_m] =>
[pts_mreg] =>
[pts_cg] => 0
)
[159] => Array
(
[pts_m] =>
[pts_mreg] => 1
[pts_cg] => 1
)
)
当我运行 count(array_filter($mm))
我得到 3
作为结果,因为它不是递归的.
When I run count(array_filter($mm))
I get 3
as result since it is not recursive.
count(array_filter($mm), COUNT_RECURSIVE)
也不行,因为我实际上需要递归运行 array_filter
,然后计算其结果.
count(array_filter($mm), COUNT_RECURSIVE)
also will not do because I actually need to run the array_filter
recursively, and then count its result.
所以我的问题是:在这种情况下如何递归运行 array_filter($mm)
?我在这里的预期结果是 4
.
So my question is: how do I recursively run array_filter($mm)
in this case?
My expected result here would be 4
.
请注意,我没有使用任何回调,因此我可以排除 false、null 和 empty.
Please note that I am not using any callback so I can exclude false, null and empty.
推荐答案
应该可以
$count = array_sum(array_map(function ($item) {
return ((int) !is_null($item['pts_m'])
+ ((int) !is_null($item['pts_mreg'])
+ ((int) !is_null($item['pts_cg']);
}, $array);
也许
$count = array_sum(array_map(function ($item) {
return array_sum(array_map('is_int', $item));
}, $array);
肯定有更多可能的解决方案.如果您想使用 array_filter()
(不带回调)请记住,它也将 0
视为 false
,因此它会删除 数组中的任何 0
值.
There are definitely many more possible solutions. If you want to use array_filter()
(without callback) remember, that it treats 0
as false
too and therefore it will remove any 0
-value from the array.
如果您在 5.3 之前的版本中使用 PHP,我会使用 foreach
-loop
If you are using PHP in a pre-5.3 version, I would use a foreach
-loop
$count = 0;
foreach ($array as $item) {
$count += ((int) !is_null($item['pts_m'])
+ ((int) !is_null($item['pts_mreg'])
+ ((int) !is_null($item['pts_cg']);
}
<小时>
更新
关于下面的评论:
Update
Regarding the comment below:
Thx @kc 我实际上希望该方法删除 false、0、empty 等
Thx @kc I actually want the method to remove false, 0, empty etc
当这真的只是你想要的时候,解决方案也很简单.但是现在不知道怎么解释
When this is really only, what you want, the solution is very simple too. But now I don't know, how to interpret
我在这里的预期结果是 5.
My expected result here would be 5.
无论如何,它现在很短:)
Anyway, its short now :)
$result = array_map('array_filter', $array);
$count = array_map('count', $result);
$countSum = array_sum($count);
结果数组看起来像
Array
(
[147] => Array
(
[pts_mreg] => 1
[pts_cg] => 1
)
[158] => Array
(
)
[159] => Array
(
[pts_mreg] => 1
[pts_cg] => 1
)
)
这篇关于如何在 PHP 数组中递归运行 array_filter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!