【问题标题】:How to automatically convert json null values to empty string in Codeigniter如何在 Codeigniter 中自动将 json null 值转换为空字符串
【发布时间】:2015-11-17 06:07:40
【问题描述】:

我正在使用 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; 

【问题讨论】:

  • 一旦你转换成字符串。用空字符串替换 null
  • 你能用例子解释一下或者给我一个链接
  • 你能告诉我echo json_encode(array('success'=> 1,'posts'=>$data));这行打印什么输出吗?
  • 这是代码 sn-p : "name":"latest", "data":[ { "timestamp":"2015-11-16 11:34:03", "avg_rating" :null } ]

标签: php json codeigniter codeigniter-2


【解决方案1】:

试试这个代码。它打印 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; 

【讨论】:

  • 我尝试了上面的代码,但同样的空值即将到来。
  • 我的代码echo 打印的内容,请告诉我$data_result 的值是什么
  • print_r($data_result);它不输出任何内容,这意味着 $data_result 中没有任何值。
  • $data_result 是一个字符串。它不是一个数组。所以,你应该使用echo
【解决方案2】:

这是最简单的方法:

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

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

【讨论】:

    猜你喜欢
    • 2013-08-21
    • 2014-06-10
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    • 2012-11-03
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多