Reputation: 137
i have a table named "class" with field "section", the section field is joined in "section" table and "course" table. Now i want to display all distinct "section" and group it with "course":
Course 1
-Section 1
-section 2
Course 2
-section 3
-section 4
here is my query code
return $this->_db->select("
SELECT DISTINCT
class.section,
section.id,
section.code,
section.name AS sectionname,
section.`year`,
section.minenrollee,
course.code,
course.name AS coursename
FROM
class
Inner Join section ON class.section = section.id
Inner Join course ON section.course = course.id
WHERE
class.period = '".$period."'
GROUP BY
section.course
ORDER BY
section.`year` ASC,
section.code ASC
");
this is my php code. can anyone help me. thanks in advance
//GET DISTINCT SECTION IN CLASS
$sections = $this->model->getDistinctsections(Session::get('period'));
$list = array();
foreach ($sections as $r) {
$list[$r->coursename][$r->id]['coursename'] = $r->coursename;
}
print_r($list);
Upvotes: 1
Views: 35
Reputation: 4539
Your data should be returning properly as is. That being said, a statement like print_r()
will never return the data grouped into a nice, "grouped" list. That's not its job; you'll have to do that on your own.
To get a result you want, you'll need to loop through your data. If a column you're grouping on is the same as the column from the previous row, then you don't need to write it to the table again. Since this isn't a coding service, I'll give you an example data set, and you can work from there.
Example Data:
Company | Department | Employee
-------------------------------
A | Accounting | John
A | Accounting | Bill
A | Billing | Jane
A | Billing | Debra
To print this data into a table, grouping on Company
and Department
, we need to loop through the data.
Rough algorithm:
Company
is null or doesn't match the current row's value, then print the Company
value.Department
is null or doesn't match the current row's value, then print the Department
value.Employee
Following this algorithm should pretty easily get you to a display like
Company | Department | Employee
-------------------------------
A | Accounting | John
| | Bill
| Billing | Jane
| | Debra
Minor adaptations from you can make it prettier. :)
Upvotes: 1