从多维数组中递归删除空元素和子数组 [英] Recursively remove empty elements and subarrays from a multi-dimensional array
问题描述
对于从PHP数组中删除空元素这一古老的问题,我似乎找不到一个简单而直接的解决方案.
I can't seem to find a simple, straight-forward solution to the age-old problem of removing empty elements from arrays in PHP.
我的输入数组可能看起来像这样:
My input array may look like this:
Array ( [0] => Array ( [Name] => [EmailAddress] => ) )
(依此类推,如果还有更多数据,尽管可能没有...)
(And so on, if there's more data, although there may not be...)
如果是上面的样子,我希望它在处理后完全为空.
If it looks like the above, I want it to be completely empty after I've processed it.
所以print_r($array);
将输出:
Array ( )
如果我运行$arrayX = array_filter($arrayX);
,我仍然会得到相同 print_r
的输出.不过,我到过的所有地方都表明这是在PHP5中删除空数组元素的最简单方法.
If I run $arrayX = array_filter($arrayX);
I still get the same print_r
output. Everywhere I've looked suggests this is the simplest way of removing empty array elements in PHP5, however.
我也尝试过$arrayX = array_filter($arrayX,'empty_array');
,但出现以下错误:
I also tried $arrayX = array_filter($arrayX,'empty_array');
but I got the following error:
警告:array_filter()[function.array-filter]:第二个参数'empty_array'应该是有效的回调
Warning: array_filter() [function.array-filter]: The second argument, 'empty_array', should be a valid callback
我在做什么错了?
推荐答案
尝试使用 array_map()
将过滤器应用于$array
中的每个数组:
Try using array_map()
to apply the filter to every array in $array
:
$array = array_map('array_filter', $array);
$array = array_filter($array);
演示: http://codepad.org/xfXEeApj
这篇关于从多维数组中递归删除空元素和子数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!