I have a mysql table as below:
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
I want to show the data from the above table such that all task_id
has to be shown as comma-separated-values for a particular date for a particular project. Let's say for project_id=1
I am listing all dates in the start_date
first, then I will show the tasks with the same start_date
will be listed as comma-separated.
The expected result is:
start_date task_id
-----------------------
2019-02-20 3
2019-12-09 4,5
I tried the to achieve the same with 2 foreach loops but I'm not getting expected results.Below is my code:
Controller:
$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);
Model
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;
}
When I try print_r($tasks)
the result is Array ( [date] => 2019-02-20 [tasks] => 4,5,3 )
.
I know this is not a complex problem, but at the moment I can't figure out the proper solution to achieve this. Is there any other efficient way to solve this?
SELECT start_date,GROUP_CONCAT(task_id) as task_id
from project
where project_id = 1
group by start_date
Your problem can be achieved using this single query.
Use DISTINCT
keyword,if same task_id
repeated in a same day.
SELECT start_date,GROUP_CONCAT(DISTINCT task_id) as task_id
FROM project
WHERE project_id = 1
GROUP BY start_date;
If you use DISTINCT
,we will get unique task_id(s)..
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.