按列和组的Json数组

k3bvogb1  于 2022-12-15  发布在  其他
关注(0)|答案(1)|浏览(108)

我有一个不同坐标的滑板车列表。
下面是我的数据库:(https://i.stack.imgur.com/56wuz.png
下面是我的PHP代码(Codeigniter)

public function getstations_post() {
    $this->db->select('*');
    $this->db->where('sc_status', 1);
    $sonuc = $this->db->from('scooterlist')->get();

    $data = array();
    foreach ($sonuc->result() as $key => $value) {
        $data['kordinatlar'] = $value->sc_position;
        $data['imei'] = $value->imei;
        $data['plate'] = $value->plate;
        $data['battery'] = $value->battery;
    }
    print_r($data);

    //$this->response(array('status' => true, 'data' => $data), REST_Controller::HTTP_OK);
}

我想按列和分隔符" | "列出,如下所示

{
    "status": true,
    "data": [
      {
        "id": 1,
        "kordinatlar": "40.39387593006866, 49.79430719189057 | 36.4239163, -122.0947212 | 37.4239163, -120.0947212",
        "imei": "123456666 | 123456777 | 123456888",
        "plate" : "NGS666 | NGS777 | NGS888",
        "battery": "100 | 20 | 23"
      },
      {
        "id": 2,
        "kordinatlar": "40.39015918722332, 49.793001900018645 | 32.4239163,-111.0947212 | 32.4239163,-111.0947212 | 32.4239163,-111.0947212",
        "imei": "987654321 | 987654321 | 987654321 | 987654341",
        "plate" : "NGS321 | NGS321 | NGS321 | NGS322",
        "battery": "10 | 22 | 35 | 50"
      }
    ]
  }

我尝试用相同的变量创建foreach(),但不起作用。

ymdaylpp

ymdaylpp1#

你需要修改你的循环代码,因为现在你一次又一次地覆盖相同的索引。

$data = array('status'=> true);
foreach ($sonuc->result() as $key => $value) {
    $data['data'][] = [
        'kordinatlar' => $value->sc_position,
        'imei' => $value->imei,
        'plate' => $value->plate,
        'battery' => $value->battery
    ];//$data['data'][] will create new child-element instead of overwriting first index data
}
print_r($data);

相关问题