给定一个数组数组,如何用 0 替换所有空值?
示例数组
$myArray[0] = array('23', null, '43', '12');
$myArray[1] = array(null, null, '53', '19');
$myArray[2] = array('12', '13', '14', null);
所有空值都应该替换为 0。我希望有人能有一种有效的方法来做到这一点,也许是我不知道的内置 PHP 函数。
Example array
$myArray[0] = array('23', null, '43', '12');
$myArray[1] = array(null, null, '53', '19');
$myArray[2] = array('12', '13', '14', null);
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
array_walk_recursive
函数,带有一个用0
替换null
的回调函数。For example, considering your array is declared this way :
注意:我认为您犯了一个拼写错误,并且您的数组不仅仅包含一个字符串,而是包含几个子元素。
You could use this kind of code :
With the following callback functon :
请注意:
===
运算符进行比较And you'd get the following output :
You could use the
array_walk_recursive
function, with a callback function that would replacenull
by0
.For example, considering your array is declared this way :
Note : I supposed you made a typo, and your arrays are not containing only a string, but several sub-elements.
You could use this kind of code :
With the following callback functon :
Note that :
===
operator for the comparisonAnd you'd get the following output :
如果单引号是无意的,并且数组具有整数和空值:
If the single quotation marks are unintentional, and the arrays have integers and null values:
从 PHP7.4 及更高版本开始,您可以使用箭头函数语法对每行迭代调用
intval()
。这对于您的数据来说是安全的,因为无条件地将输入值转换为int
类型数据不会损坏任何输入值。代码:(演示)
From PHP7.4 and higher, you can use arrow function syntax to make iterated calls of
intval()
on each row. This is safe to use on your data because none of the input values will be damaged by unconditionally casting them toint
type data.Code: (Demo)