【问题标题】:how to change the format of json value data in codeigniter如何在codeigniter中更改json值数据的格式
【发布时间】:2018-03-23 08:35:51
【问题描述】:

我正在尝试使用预定义的 json 格式为插件显示数据,但我尝试后数据与格式不匹配怎么回事?

需要 JSON

[
  {
    latLng: [-6.17343444,1206.834234294],
    name: 'XY'
  },
  {
    latLng: [-6.1742343244,106.898987294],
    name: 'XK'
  }
]

结果我的 JSON

[
  {
    "latLng": "-6.17343444,1206.834234294",
    "name": "XK"
  },
  {
    "latLng": "-6.1742343244,106.898987294",
    "name": "XY"
  }
]

我的脚本 PHP

public function lat_lang() {
    foreach($this->model->name_model() as $row){    
        $data[] = array(
            'latLng' => $row->lat_long,
            'name' => $row->city
          );                                
    }
        header('content-type: application/json');   
        echo json_encode($data);    
}

调用 JSON

$.parseJSON('<?php echo base_url().'mycontrollers';?>', function(datas) {
    console.log(datas);
});

【问题讨论】:

    标签: php json codeigniter


    【解决方案1】:

    您可以使用explode() 将字符串"-6.17343444,1206.834234294" 转换为数组[-6.17343444,1206.834234294]

    public function lat_lang() {
        foreach($this->model->name_model() as $row){    
            $data[] = array(
                'latLng' => explode(',',$row->lat_long),
                'name' => $row->city
              );                                
        }
            header('content-type: application/json');   
            echo json_encode($data);    
    }
    

    如果您想获得浮点数(对于 JSON 中的所有值),您可以使用 JSON_NUMERIC_CHECK:

    json_encode($data, JSON_NUMERIC_CHECK);
    

    或者,仅针对特定值:

    $latLng = explode(',', $row->lat_long);
    $latLng = array_map('floatval', $latLng);
    $data[] = array(
        'latLng' => $latLng,
        'name' => $row->city
      ); 
    

    【讨论】:

    • 谢谢,@Syscall 谢谢,依旧不变,json 结果上还有引号"latLng": ["-6.17343444", "1206.834234294"]
    • @irwandwiyanto 你可以试试json_encode($data, JSON_NUMERIC_CHECK);
    • @irwandwiyanto 我已经用另一种强制浮点值的方式更新了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-18
    • 2014-05-03
    • 2018-02-18
    • 1970-01-01
    相关资源
    最近更新 更多