将json_encode中的null转换为空字符串?

时间:2018-06-01 01:07:45

标签: php arrays json string

我在尝试使用json_encode的结果将空值转换为空字符串时遇到问题:

    if ($uresult->num_rows >0) {


 while($urow = $uresult->fetch_assoc()) {


 $rresult = mysqli_query($con,"SELECT * FROM allid WHERE postid='$oldid' AND spaceid='$newid'");
 $lrow = mysqli_fetch_assoc($rresult);
 $tem = $lrow['postid'];

 $ujson = json_encode($tem);
 echo $ujson;
 }

} else {
}

以下是$ujson

的结果
"10"nullnullnullnull"25"

我找到了答案,我得到了这个答案:

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

这样做会导致我收到此错误:

Warning: array_walk() expects parameter 1 to be array, string given

这是将null转换为空字符串的正确方法,如果是这样,我做错了什么?

2 个答案:

答案 0 :(得分:2)

就像我在评论中所说的那样,它说$temstringarray_walk需要一个数组才能正常工作。

无论如何,如果您打算将null值转换为空字符串'',只需array_map strval所有数组,以便适用strval数组中的每个元素。最后,编码。

以下是一般概念:

$lrow = array_map('strval', $lrow);

更深入地了解,您应该首先将所有项目放在容器中,然后最终对它们进行编码。不要对每个批次进行编码。关于$tem,那么你不需要array_walk,只需要一个三元运算符:

$post_ids = array();
if ($uresult->num_rows > 0) {
    while ($urow = $uresult->fetch_assoc()) {
        $rresult = mysqli_query($con,"SELECT * FROM allid WHERE postid='$oldid' AND spaceid='$newid'");
        $lrow = mysqli_fetch_assoc($rresult);
        $tem = !is_null($lrow['postid']) ? $lrow['postid'] : '';
        $post_ids[] = $tem;
    }
}

echo json_encode($post_ids);

旁注:尽可能避免使用while循环,并在其中使用另一个查询(假设有一千行;它也会查询一千次)。请改用JOIN语句。

答案 1 :(得分:1)

尝试这种方式-

//Array
$array = ["id" => 1, "name" => "Rohit Suthar", "city" => null, "mobile" => null];

//Convert null value to empty string 
array_walk_recursive($array,function(&$item){$item=strval($item);});

echo json_encode($array);