给定一个数组数组,如何将所有空值替换为0? [英] Given an array of arrays, how can I replace all empty values with 0?
本文介绍了给定一个数组数组,如何将所有空值替换为0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
示例数组
$myArray[0] = array('23', null, '43', '12');
$myArray[1] = array(null, null, '53', '19');
$myArray[2] = array('12', '13', '14', null);
所有null都应替换为0.我希望有人能够以一种有效的方式做到这一点,也许是我不知道的内置PHP函数.
All nulls should be replaced with 0. I was hoping someone would have an efficient way of doing this, perhaps a built in PHP function that I am unaware of.
推荐答案
您可以使用 array_walk_recursive
函数,其回调函数将 null
替换为 0
.
You could use the array_walk_recursive
function, with a callback function that would replace null
by 0
.
例如,考虑以这种方式声明数组:
For example, considering your array is declared this way :
$myArray[0] = array(23, null, 43, 12);
$myArray[1] = array(null, null, 53, 19);
$myArray[2] = array(12, 13, 14, null);
注意:我以为您输入了错字,并且您的数组不仅包含一个字符串,还包含多个子元素.
您可以使用这种代码:
You could use this kind of code :
array_walk_recursive($myArray, 'replacer');
var_dump($myArray);
使用以下回调functon:
With the following callback functon :
function replacer(& $item, $key) {
if ($item === null) {
$item = 0;
}
}
请注意:
- 第一个参数通过引用传递!
- 这意味着对其进行修改将修改您数组中的相应值
然后您将得到以下输出:
And you'd get the following output :array 0 => array 0 => int 23 1 => int 0 2 => int 43 3 => int 12 1 => array 0 => int 0 1 => int 0 2 => int 53 3 => int 19 2 => array 0 => int 12 1 => int 13 2 => int 14 3 => int 0
这篇关于给定一个数组数组,如何将所有空值替换为0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文