如何将 php 数组中的 null 值转换为空字符串?
我想转换这个数组,Array[4] 不应该给出 null 它可以给出空格(空字符串)。
Array (
[0] => 1
[1] => 4
[2] => 0
[3] => V
[4] =>
[5] => N
);
(更改原因,与一般问题无关)
Fatal error: Uncaught exception
'PDOException' with message 'Database
error [23000]: Column 'message' cannot
be null, driver error code is 1048' in
I want to convert this array that Array[4] should not give null it can give blank space (empty string).
Array (
[0] => 1
[1] => 4
[2] => 0
[3] => V
[4] =>
[5] => N
);
(The reason for the change, unrelated to the general question)
Fatal error: Uncaught exception
'PDOException' with message 'Database
error [23000]: Column 'message' cannot
be null, driver error code is 1048' in
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
PHP 5.3+
PHP 5.3+
然后,您应该循环遍历数组元素,检查每个值是否为 null 并将其替换为空字符串。类似的东西:
另外,您可以实现检查功能并使用 array_map()< /a> 函数。
Then you should just loop through array elements, check each value for null and replace it with empty string. Something like that:
Also, you can implement checking function and use array_map() function.
还有更好/更短/更简单的解决方案。已给出答案的汇编。对于初始数据
$result 将是
即使在 php4 中这也应该可以工作:)
There is even better/shorter/simpler solution. Compilation of already given answers. For initial data
with
$result will be
This should work even in php4 :)
这会将数组映射到一个新数组,该数组利用 null 三元运算符来包含数组的原始值,或者包含空字符串(如果该值为 null)。
This will map the array to a new array that utilizes the null ternary operator to either include an original value of the array, or an empty string if that value is null.
你可以用这个代替。
You can use this instead.
这是我在上面的答案中没有提到的一种技术:
这对于
$_GET
参数加载非常方便,可以使内容简短易读。另外,您可以将strval()
替换为trim()
...或者如果您只接受整数,则可以替换为intval()
。如果缺少或非数字值,
intval
的默认值为0
。如果为空、null 或 false,则strval
的默认值为""
。查看 DEMO
现在对于数组,您仍然需要循环遍历每个值并设置它。但它非常可读,IMO:
这是结果:
有趣的是,
true
变成了“1”,但是'true'
仍然是一个字符串,而false
变成了空字符串""< /代码>。
现在使用
$arr[$key] = intval($value);
的相同数据会产生以下结果:Here's a technique I haven't seen mentioned in the above answers:
This is super handy for
$_GET
parameter loading to keep things short and readable. Bonus, you can replacestrval()
withtrim()
... or withintval()
if you only accept integers.The default for
intval
will be0
if missing or a non-numeric value. The default forstrval
is""
if empty, null or false.See DEMO
Now for an array, you'll still need to loop over every value and set it. But it's very readable, IMO:
Here is the result:
Interesting is that
true
becomes "1", but'true'
stays a string and thatfalse
becomes and empty string""
.Now the same data using
$arr[$key] = intval($value);
produces this result:使用此功能。这会将嵌套数组中的 null 替换为空字符串,
输出也将是:
在此处在线尝试:https://3v4l.org/7uXTL< /a>
Use this function. This will replace null to empty string in nested array also
Output will be :
Try online here : https://3v4l.org/7uXTL
这可以使用一行解决:
这里 $array_json_return 是数组。
This can be solved in one line using:
here $array_json_return is the array.