如何在Codeigniter中将json空值自动转换为空字符串

问题描述 投票:0回答:2

我正在Codeigniter中使用json,并且我有一些字段会输出空值,我想将这些空值更改为空字符串。我不想一一检查每个字段。我的CI代码如下:

$result= $this->get_model->get_model();
header("content-type: application/json");
$data[] = array('name'=>"result",'data'=>$result);
echo json_encode(array('success'=> 1,'posts'=>$data));
return $result; 

enter image description here

php json codeigniter codeigniter-2
2个回答
0
投票

尝试此代码。它输出json并将空值替换为空

$result= $this->get_model->get_model();
header("content-type: application/json");
$data[] = array('name'=>"result",'data'=>$result);
$data_result = json_encode(array('success'=> 1,'posts'=>$data));

echo str_replace("null","",$data_result);

return $result; 

0
投票

这是最简单的方法:

array_walk_recursive($array,function(&$item){$item=strval($item);});

发件人:https://developertipsandtricks.blogspot.com/2013/10/convert-null-to-empty-string-for-json.html

© www.soinside.com 2019 - 2024. All rights reserved.