我试图在codeigniter中为每个chkey获取一个数据,其中包含一个相关的值作为一个组。当有2个或更多的chkey时,则代码正常工作。但当只有一个chkey时,它会显示该chkey的值,但它会显示额外的值chkey:null,value:null in json。chkey的相关json为1,如下所示
[{"unit_id":"8","CHGRAPHUpdatetime":{"time":"2018-03-15 00:00:00,2018-03-15 00:00:00,2018-03-15 00:00:00,2018-03-15 00:00:00"},"channelGraph":[{"chkey":"ch1","list":"2,-30,12,20"},{"chkey":"null","list":"null"}]}]
预期是,
[{"unit_id":"8","CHGRAPHUpdatetime":{"time":"2018-03-15 00:00:00,2018-03-15 00:00:00,2018-03-15 00:00:00,2018-03-15 00:00:00"},"channelGraph":[{"chkey":"ch1","list":"2,-30,12,20"}]}]
你能帮我解决这个问题吗。
型号代码-
public function chGraph($unitid){
$this->db->select("unit_id");
$this->db->from("device_unit");
$this->db->where('unit_id', $unitid);
$query = $this->db->get();
$unit = $query->result_array();
$j = 0;
foreach($unit as $row) {
$unit[$j]['CHGRAPHUpdatetime'] = $this->UnitCHGRAPHUpdatetime($row['unit_id']);
$unit[$j++]['channelGraph'] = $this->UnitCHGRAPHDetails1($row['unit_id']);
}
return $unit;
}
public function UnitCHGRAPHDetails1($unit_id)
{
$this->db->select('distinct(chkey)','chvalue');
$this->db->from('channel_info');
$query = $this->db->get();
$channelgraphData = $query->result_array();
$m = 0;
foreach($channelgraphData as $row) {
$chvalueQuery = 'SELECT chkey, GROUP_CONCAT(chvalue)as list FROM channel_info where chkey= "'. $row['chkey'] .'" and unit_id='. $unit_id .'';
$response = $this->db->query($chvalueQuery)->row();
$channelgraphData[$m++] = $response;
}
return $channelgraphData;
}
控制器代码-
public function chGraph()
{
$unitid = $this->uri->segment('3');
$GraphDetails = $this->device_model->chGraph($unitid);
echo json_encode($GraphDetails);
}
1条答案
按热度按时间gorkyyrv1#
你可以加一个
GROUP BY
在语句的末尾消除null
结果: