我有一个mysql表如下:
t_id project_id task_id start_date
---------------------------------------
1 29 1 2020-03-09
2 29 2 2020-02-09
3 1 3 2019-02-20
4 1 4 2019-12-09
5 1 5 2019-12-09
我想显示上表中的数据,以便所有数据都task_id必须显示为特定项目的特定日期的逗号分隔值。假设project_id=1我start_date首先列出所有日期,然后我将显示相同的任务start_date将被列为逗号分隔。
预期结果是:
start_date task_id
-----------------------
2019-02-20 3
2019-12-09 4,5
我尝试使用 2 个 foreach 循环来实现相同的效果,但没有得到预期的结果。下面是我的代码:
控制器:
$id = $this->uri->segment(4);
$dates = $this->Timesheet_model->get_tasks_dates($id); //get the dates
foreach($dates as $d)
{
$rows = $this->Timesheet_model->get_project_tasks_by_date($id,$d->start_date); //get tasks for each date
foreach($rows->result() as $res)
{
$t[] = $res->task_id;
}
$ts = implode(",",$t);
$tasks = array(
'date'=>$d->start_date,
'tasks'=>$ts
);
}
print_r($tasks);
模型
public function get_tasks_dates($id)
{
$sql = 'SELECT DISTINCT (start_date) FROM xin_tasks WHERE project_id = ? ORDER BY start_date DESC ';
$binds = array($id);
$query = $this->db->query($sql, $binds);
return $query->result();
}
public function get_project_tasks_by_date($id,$d)
{
$sql = 'SELECT task_id FROM xin_tasks WHERE project_id = ? AND start_date = ?';
$binds = array($id,$d);
$query = $this->db->query($sql, $binds);
return $query;
}
当我尝试print_r($tasks)结果是Array ( [date] => 2019-02-20 [tasks] => 4,5,3 ).
我知道这不是一个复杂的问题,但目前我无法找到实现这一目标的正确解决方案。有没有其他有效的方法来解决这个问题?
弑天下