用数组php中的空值替换空字符串
很抱歉,我对这个问题进行了大量研究.是否有标准函数来搜索和替换数组元素?
I'm sorry but i researched a lot about this issue. Is there a standard function to search and replace array elements?
str_replace 在这种情况下不起作用,因为我想搜索的是一个空字符串 '' 而我想用空值替换它们
str_replace doesn't work in this case, because what i wanna search for is an empty string '' and i wanna replace them with NULL values
这是我的数组:
$array = (
'first' => '',
'second' => '',
);
我希望它变成:
$array = (
'first' => NULL,
'second' => NULL,
);
当然我可以创建一个函数来做到这一点,我想知道是否有一个标准函数来做到这一点,或者至少是一个单行解决方案".
Of course i can create a function to do that, I wanna know if there is one standard function to do that, or at least a "single-line solution".
推荐答案
我觉得没有这样的功能,所以我们新建一个
I don't think there's such a function, so let's create a new one
$array = array(
'first' => '',
'second' => ''
);
$array2 = array_map(function($value) {
return $value === "" ? NULL : $value;
}, $array); // array_map should walk through $array
// or recursive
function map($value) {
if (is_array($value)) {
return array_map("map", $value);
}
return $value === "" ? NULL : $value;
};
$array3 = array_map("map", $array);
相关文章