我试图用NULL替换空字段值,但似乎无法弄清楚如何做到这一点。我试过array_map
、array_filter
和array_walk
,但都无济于事。例子:
function replaceWithNull($var)
{
if (empty($var) || $var == ' ') {
$var = "NULL";
}
}
array_walk($_POST, "replaceWithNull");
将保持为空/空白。我错过了什么?
为了改变数组中的元素,必须使用引用来传递参数:
function replaceWithNull(&$var)
{
...
}
否则,您将只更改变量的一个副本。
阅读这里:http://www.php.net/manual/en/functions.arguments.php
您只修改了变量的本地副本。必须通过引用传递值来修改实际数组中的值:
function replaceWithNull(&$var)
{
if (empty($var) || $var == ' ') {
$var = "NULL";
}
}
大家看这段代码:
config。
<?php
if( is_array( $_POST ) and count( $_POST ) > 0 )
{
foreach( $_POST as $key => $value )
{
if( is_array( $value ) )
{
foreach( $value as $k => $val )
{
if( is_string( $val ) )
{
if( empty($val) OR strlen(preg_replace("/('s+)?/", $val)) == 0 )
{
$_POST[$key][$k] = null;
}
}
}
}else{
if( empty($value) OR strlen(preg_replace("/('s+)?/", $value)) == 0 )
{
$_POST[$key] = null;
}
}
}
}
?>
测试:
<?php
var_dump( $_POST );
exit;
?>
myApp.php
<?php
include( 'config.php');
//.... your code here....
if(is_null( $_POST['firstname'] ))
{
echo 'hey men! error!';
}
?>