我试图在codeigniter中以组的形式获取每个chkey的相关值的数据。如果有2个或更多的chkey,则代码正常工作。
但当只有1个chkey时,它会显示该chkey的值,但在json中会显示额外的chkey:null,value:null。
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);
  }

最佳答案

您可以在语句末尾添加一个GROUP BY来消除null结果:

    $chvalueQuery = 'SELECT chkey, GROUP_CONCAT(chvalue)as list FROM channel_info where chkey= "'. $row['chkey'] .'"  and unit_id='. $unit_id .' GROUP BY chkey';

07-25 23:13