从多维数组中递归删除空元素和子数组 [英] Recursively remove empty elements and subarrays from a multi-dimensional array

查看:30
本文介绍了从多维数组中递归删除空元素和子数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于在 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); 我仍然得到 same 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆