id sender_id receiver_id msg date_added
1 2 5 hii 2018-10-24 16:42:41
2 5 2 hello 2018-10-25 16:42:41
我想将数据提取为:
[2018-10-24]=>[{
sender_id=>2,
receiver_id=>5,
msg=>hii}],
[2018-10-25]=>[{
sender_id=>5,
receiver_id=>2,
msg=>hello
}]
我首先通过查询日期并将group by应用于日期来做到这一点。 然后遍历日期并查找这些日期的数据。但是我认为在这么多的日期中使用循环以及太多的用户会使应用在未来的将来变慢
我使用的代码如下:
//the dates is used to get the dates from table using group by
$dates = $this->get_date_list($checkArr);
////then i loop through each date to get the corresponding data
foreach($dates as $key=>$value){
$msg = $this->get_msg_by_date($value,$checkArr);
$data[$value] = $msg;
}
//here is the code to get the date from the date column
public function get_date_list($checkArr){
$sql = "Select date(date_added) as new_date from tb_chats where (sender_id = $checkArr[sender_id] AND receiver_id = $checkArr[receiver_id]) OR (sender_id = $checkArr[receiver_id] AND receiver_id = $checkArr[sender_id]) GROUP BY new_date";
$query = $this->db->query($sql);
$data = $query->result_array();
return array_column($data,'new_date');
}
//here is the code to get the data for the looped dates
public function get_msg_by_date($date,$checkArr){
$sql = "Select * from tb_chats where (sender_id = $checkArr[sender_id] AND receiver_id = $checkArr[receiver_id] AND date_added LIKE '$date%') OR (sender_id = $checkArr[receiver_id] AND receiver_id = $checkArr[sender_id] AND date_added LIKE '$date%')";
$query = $this->db->query($sql);
$data = $query->result_array();
return $data;
}
答案 0 :(得分:0)
将日期字段作为逗号分隔的字符串连同查询( CONCAT )一起使用。 使用 array_combine 方法。第一个参数是 explode(',',CONCAT STRING)的输出,第二个参数是结果数组。输出就是您想要的。