【问题标题】:How to remove double quotes from json_encode in php? [duplicate]如何从 php 中的 json_encode 中删除双引号? [复制]
【发布时间】:2019-03-04 05:57:49
【问题描述】:

代码:

<?php
    if(!isset($candidate_id))
    {
        header("location:".base_url()."login");
    }
    $this->db->select('event,event_title,description,s_date');
    $this->db->from('event');
    $this->db->where('candidate_id',$cid);
    $this->db->order_by('s_date','desc');
    $query = $this->db->get();
    if($query->num_rows() > 0)
    {
        $result = $query->result_array();
        $record = array();
        foreach($result as $row)
        {
            $record[] = $row;
        }
        echo json_encode($record,JSON_NUMERIC_CHECK);
    }
    else
    {
        $this->session->set_flashdata('no_event',"<p>No event Added</p>");
    }
?>

当前输出:

[{"event":"2019-03-06","event_title":"meeting","description":"meeting with xyz","s_date":"2019-03-04"}]

预期输出:

[{event:"2019-03-06",event_title:"meeting",description:"meeting with xyz",s_date:"2019-03-04"}]

我正在使用 json_encode() 函数创建一个简单的 JSON API。现在,我成功创建了 API,但正如我上面提到的,输出是意外的。现在,我真正想要的我也在上面提到。那么,如何获得预期的输出?请帮帮我。

谢谢

【问题讨论】:

  • 您的预期输出是不是 JSON - 无论您需要它用于哪个软件,如果您可以访问它 - 修复它!如果您无权访问,请告诉必须修复它的人。

标签: php json api codeigniter


【解决方案1】:

问题是,如果您从键中删除引号,它就不再是 JSON。我假设您希望它类似于 JavaScript 对象,但这应该在客户端使用 JSON.parse() 完成。

即:

var apiResponse = '[{"event":"2019-03-06","event_title":"meeting","description":"meeting with xyz","s_date":"2019-03-04"}]';

var json = JSON.parse(apiResponse);

console.log(json);
console.log(json[0].description);

【讨论】:

    【解决方案2】:

    试试这个

    $array_final = preg_replace('/"([a-zA-Z_]+[a-zA-Z0-9_]*)":/','$1:',json_encode($you-array));
    

    输出

    {event:"2019-03-06",event_title:"meeting",description:"meeting with xyz",s_date:"2019-03-04"} 
    

    【讨论】:

      猜你喜欢
      • 2019-02-15
      • 1970-01-01
      • 2014-02-17
      • 1970-01-01
      • 2018-02-14
      • 2014-07-18
      • 2014-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多