我有一个表,我想从数据库中获取数据并将其返回到JSON fromat date vise中,下面是我的表:
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"
}
]
]
}
虽然您提供的结果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
)));
}
?>