我在尝试使用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转换为空字符串的正确方法吗?如果是,我做错了什么?
发布于 2018-06-01 09:20:46
就像我在评论中说的那样,它说$tem
是一个string
。array_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
语句。
发布于 2020-07-29 02:34:54
试着这样做-
//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);
https://stackoverflow.com/questions/50634768
复制相似问题