我有一张桌子,我希望从数据库中获取数据并将其返回到 JSON fromat 日期老虎钳,下面是我的表格:
id userId Date Time record
1 1 15-Oct-2017 3:50 152
2 1 15-Oct-2017 4:30 142
3 1 16-Oct-2017 8:50 130
4 2 15-Oct-2017 2:00 90
5 2 15-Oct-2017 4:50 154
6 2 15-Oct-2017 5:00 120
我创建了一个函数,在其中我从数据库调用数据并返回 JSON fromat
中的输出public function getRecord()
{
$userId = $this->input->get('userId');
$this->db->from('xyz');
$this->db->where('userId',$userId);
$record = $this->db->get()->result();
return $this->output->set_output(json_encode(array(
'status' => 'Ok',
'statusCode' =>'801',
'response' => $record
)));
}
它给我这样的东西,这是我不需要的(我知道我没有以正确的方式去做)
{
"status": "Ok",
"statusCode": "801",
"response": Array[3][
{
"id": "1",
"userId": "1",
"date": "15-Oct-2017",
"time": "3:50",
"record": "152"
},
{
"id": "2",
"userId": "1",
"date": "15-Oct-2017",
"time": "4:30",
"record": "142"
},
{
"id": "3",
"userId": "1",
"date": "16-Oct-2017",
"time": "8:50",
"record": "130"
}
]
}
但是我想要这样的东西,输出将被放入日期虎钳
{
"status": "Ok",
"statusCode": "801",
"response": Array[3][
[
"date": "15-Oct-2017"
{
"id": "1",
"userId": "1",
"date": "15-Oct-2017",
"time": "3:50",
"record": "152"
},
{
"id": "2",
"userId": "1",
"date": "15-Oct-2017",
"time": "4:30",
"record": "142"
}
],
[
"date": "16-Oct-2017"
{
"id": "3",
"userId": "1",
"date": "16-Oct-2017",
"time": "8:50",
"record": "130"
}
]
]
}
答案 0 :(得分:1)
虽然您提供的结果json似乎没有效果,因此,我认为您希望按日期分组的记录,尝试循环记录数组,按日期将它们分组到另一个数组上:
<?php
public function getRecord()
{
$userId = $this->input->get('userId');
$this->db->from('xyz');
$this->db->where('userId',$userId);
$record = $this->db->get()->result();
$orderedRecord = [];
foreach ($record as $r) {
if (!isset($orderedRecord[$r->Date])) {
$orderedRecord[$r->Date] = [];
}
$orderedRecord[$r->Date][] = $r;
}
return $this->output->set_output(json_encode(array(
'status' => 'Ok',
'statusCode' =>'801',
'response' => $orderedRecord
)));
}
?>