php 如何将空值转换为php数组中的空字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4827854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 14:30:35  来源:igfitidea点击:

How to convert the null values to empty string in php array?

phparraysnull

提问by XMen

I want to convert this array that Array[4] should not give null it can give blank space (empty string).

我想转换这个数组, Array[4] 不应该给 null 它可以给空格(空字符串)。

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

回答by MythThrazz

PHP 5.3+

PHP 5.3+

    $array = array_map(function($v){
        return (is_null($v)) ? "" : $v;
    },$array);

回答by Kel

Then you should just loop through array elements, check each value for null and replace it with empty string. Something like that:

然后你应该循环遍历数组元素,检查每个值是否为空并将其替换为空字符串。类似的东西:

foreach ($array as $key => $value) {
    if (is_null($value)) {
         $array[$key] = "";
    }
}

Also, you can implement checking function and use array_map()function.

此外,您可以实现检查功能并使用array_map()功能。

回答by hexiecode

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.

这会将数组映射到一个新数组,该数组使用空三元运算符来包含数组的原始值,或者如果该值为空则包含一个空字符串。

$array = array_map(function($v){
    return $v ?: '';
},$array);

回答by Anton Kolenkov

There is even better/shorter/simpler solution. Compilation of already given answers. For initial data

还有更好/更短/更简单的解决方案。已经给出答案的汇编。对于初始数据

[1, 4, "0", "V", null, false, true, 'true', "N"]
[1, 4, "0", "V", null, false, true, 'true', "N"]

with

$result = array_map('strval', $arr);

$resultwill be

$result将是

['1', '4', '0', 'V', '', '', '1', 'true', 'N']
['1', '4', '0', 'V', '', '', '1', 'true', 'N']

This should work even in php4 :)

即使在 php4 中,这也应该可以工作 :)

回答by rrCKrr

You can use this instead.

您可以改用它。

array_map(function($val){return is_null($val)? "" : $val;},$result);

回答by TrophyGeek

Here's a technique I haven't seen mentioned in the above answers:

这是我在上述答案中没有看到的一种技术:

$val = strval(@$arr["notfound"]);  // will not generate errors and
                                   // defaults to an empty string

This is super handy for $_GETparameter loading to keep things short and readable. Bonus, you can replace strval()with trim()... or with intval()if you only accept integers.

这对于$_GET参数加载来说非常方便,可以使内容简短易读。奖励,您可以替换strval()trim()... 或者intval()如果您只接受整数。

The default for intvalwill be 0if missing or a non-numeric value. The default for strvalis ""if empty, null or false.

默认intval将是0,如果丢失或者非数字的值。默认strval""如果为空,空或假的。

$val_str = strval(@$_GET['q']);
$val_int = intval(@$_GET['offset']);

See DEMO

见演示

Now for an array, you'll still need to loop over every value and set it. But it's very readable, IMO:

现在对于数组,您仍然需要遍历每个值并设置它。但它非常易读,IMO:

$arr = Array (1, 4, "0", "V", null, false, true, 'true', "N");

foreach ($arr as $key=>$value) {
  $arr[$key] = strval($value);
}

echo ("['".implode("','", $arr)."']");

Here is the result:

结果如下:

['1','4','0','V','','','1','true','N']
['1','4','0','V','','','1','true','N']

Interesting is that truebecomes "1", but 'true'stays a string and that falsebecomes and empty string "".

有趣的是它true变成了“1”,但'true'仍然是一个字符串,然后false变成了空字符串""

Now the same data using $arr[$key] = intval($value);produces this result:

现在使用相同的数据$arr[$key] = intval($value);产生这个结果:

['1','4','0','0','0','0','1','0','0']
['1','4','0','0','0','0','1','0','0']

回答by Vivek Pipaliya

Use this function. This will replace null to empty string in nested array also

使用此功能。这也将在嵌套数组中将 null 替换为空字符串

$arr = array(
          "key1"=>"value1",
          "key2"=>null,
          "key3"=>array(
                 "subkey1"=>null, 
                 "subkey2"=>"subvalue2"),
          "key4"=>null);

    echo json_encode(replace_null_with_empty_string($arr));

   function replace_null_with_empty_string($array)
    {
        foreach ($array as $key => $value) 
        {
            if(is_array($value))
                $array[$key] = replace_null_with_empty_string($value);
            else
            {
                if (is_null($value))
                    $array[$key] = "";
            }
        }
        return $array;
    }

Output will be :

输出将是:

{
  "key1": "value1",
  "key2": "",
  "key3": {
    "subkey1": "",
    "subkey2": "subvalue2"
  },
  "key4": ""
}

Try online here : https://3v4l.org/7uXTL

在线尝试:https: //3v4l.org/7uXTL

回答by ayush

foreach($array as $key=>$value)
{
if($value===NULL)
{
$array[$key]="";
}
}

回答by R. Gurung

This can be solved in one line using:

这可以在一行中使用以下方法解决:

array_walk($array_json_return,function(&$item){$item=strval($item);});

here $array_json_return is the array.

这里 $array_json_return 是数组。