其他分享
首页 > 其他分享> > 循环返回条件查询中的一个结果

循环返回条件查询中的一个结果

作者:互联网

我试图在代码点火器中从数据库中获取数据.Bur此循环仅返回一个循环.

$userchatData = $this->db->get($this->db->dbprefix('usres_chat'))->result_array();

 foreach($userchatData as $key => $userdata)
 {
       $userdatas[]= array(
                  'chat_id' => $userdata['chat_id'],
                  'chat_from' => $userdata['chat_from'],
                  'created_date' => $userdata['created_date']
           );
 }
 $data['ChatdatabyId'] = $userdatas;
 $data['responseCode'] = '200';

 $data['responseMessage'] = 'User listing successfully';

 echo json_encode($data);

解决方法:

您需要定义$userdatas = array();在循环之外.正是在循环内部,这才是它覆盖数据并返回最后一条记录的原因.

$userchatData = $this->db->get($this->db->dbprefix('usres_chat'))->result_array();
  $userdatas = array();
  foreach($userchatData as $key => $userdata){
  $userdatas[]= array(
                 'chat_id' => $userdata['chat_id'],
                 'chat_from' => $userdata['chat_from'],
                 'created_date' => $userdata['created_date']
                 );
  }
   $data['ChatdatabyId'] =$userdatas;
   $data['responseCode'] = '200';
   $data['responseMessage'] = 'User listing successfully';
   echo json_encode($data);

标签:codeigniter-3,php
来源: https://codeday.me/bug/20191109/2010859.html