在我的表courses
中,我有几个共享相同academy_id
值的条目。我使用foreach循环来检索具有相同academy_id
的所有行。在下面的例子中,有一个学院有两门课程。值正确显示,但显示了一些不必要的值。例如,它会创建两个结果。是否可以在wanted result to display
部分中显示如下所示的一个组合结果?
PHP
$academy_id = 123
$db_select = $db_con->prepare("
SELECT ca.course_name,
ca.course_start_date,
ca.course_end_date
FROM courses_by_academy ca
WHERE ca.academy_id = :academy_id
");
$final_result = '';
if (!$db_select) return false;
if (!$db_select->execute(array(':academy_id' => $academy_id))) return false;
$results = $db_select->fetchAll(\PDO::FETCH_ASSOC);
if (empty($results)) return false;
foreach ($results as $value){
$final_result .= "<b>Academy Name: </b>".$value['name']."</br><b>Academy Type: </b>".$value['type']."</br><b>Status: </b>".$value['status']."</br>";
$final_result .= "<b>Course Name: </b>".$value['course_name']."</br><b>Start Date: </b>".$value['course_start_date']."</br><b>End Date: </b>".$value['course_end_date']."</br>";
}
}
表值
+----+------------+----------------------+---------------+------------+
| id | academy_id | course_name | start_date | end_date |
+----+------------+----------------------+---------------+------------+
| 1 | 123 | Biology - Basic | 2013-11-30 | 2013-12-25 |
| 2 | 123 | Biology - Nutrition | 2014-01-15 | 2014-01-25 |
+----+------------+----------------------+---------------+------------+
显示当前结果
Academy Name: North Valley Schools
Academy Type: Post-Secondary
Status: INACTIVE
ID: 123
Course Name: Biology - Basic
Start date: 2013-11-30
End date: 2013-12-25
Academy Name: North Valley Schools
Academy Type: Post-Secondary
Status: INACTIVE
ID: 123
Course Name: Biology - Nutrition
Start date: 2014-01-15
End date: 2014-01
通缉结果 - 合并
Academy Name: North Valley Schools
Academy Type: Post-Secondary
Status: INACTIVE
ID: 123
Course Name: Biology - Basic
Start date: 2013-11-30
End date: 2013-12-25
Course Name: Biology - Nutrition
Start date: 2014-01-15
End date: 2014-01-25
答案 0 :(得分:1)
你的循环:
foreach ($results as $value){
$final_result .= "<b>Academy Name: </b>".$value['name']."</br><b>Academy Type: </b>".$value['type']."</br><b>Status: </b>".$value['status']."</br>";
$final_result .= "<b>Course Name: </b>".$value['course_name']."</br><b>Start Date: </b>".$value['course_start_date']."</br><b>End Date: </b>".$value['course_end_date']."</br>";
}
代替:
$first = true;
foreach ($results as $value){
if($first){
$first = false;
$final_result .= "<b>Academy Name: </b>".$value['name']."</br><b>Academy Type: </b>".$value['type']."</br><b>Status: </b>".$value['status']."</br>";
}
$final_result .= "<b>Course Name: </b>".$value['course_name']."</br><b>Start Date: </b>".$value['course_start_date']."</br><b>End Date: </b>".$value['course_end_date']."</br>";
}
它只会执行一次学院信息。 :)