我做了这样一个mysql查询
SELECT
forum_subcategories.name_sub,
forum_categories.id,
forum_categories.name
FROM
forum_subcategories
LEFT JOIN forum_categories ON forum_subcategories.catid = forum_categories.id
当我这样回应时
while($row = $result->fetch_assoc()){
echo '<h3><strong>'.$row['name'].' - '.$row['id'].'</strong></h3>';
echo '<h4>'.$row['name_sub'].' - '.$row['id'].'</h4>';
我得到以下结果:
Category-1
subcategory belonging to 1
Category-1
subcategory belonging to 1
Category-2
subcategory belonging to 2
Category-2
subcategory belonging to 2
Category-3
subcategory belonging to 3
Category-3
subcategory belonging to 3
但是我要找的结果是这样的:
Category-1
subcategory belonging to 1
subcategory belonging to 1
Category-2
subcategory belonging to 2
subcategory belonging to 2
Category-3
subcategory belonging to 3
subcategory belonging to 3
我将如何实现这个结果?
最佳答案
您的查询实际上是正确的,这只是仅在类别发生更改时将其作为输出发送的问题。将类别存储在变量中,并在每次循环迭代时检查新值是否与旧值匹配。如果没有,打印出来。
// variable to hold the current one...
// It starts empty.
$current_category = '';
// Remember whether there's a <div> unclosed
$subcat_div_open = false;
while($row = $result->fetch_assoc()){
// Compare to the category of the loop iteration
if ($row['name'] !== $current_category) {
// If there's a subcategory <div> open, close it
if ($subcat_div_open) {
echo '</div>';
}
echo '<h3><strong>'.$row['name'].' - '.$row['id'].'</strong></h3>';
// Store the new one to compare next time around
$current_category = $row['name'];
// Ouput an opening <div> for the subcategories
// and keep track of its state
echo '<div>';
$subcat_div_open = true;
}
// Always output the subcategory
echo '<h4>'.$row['name_sub'].' - '.$row['id'].'</h4>';
}
// Clean up the open div
if ($subcat_div_open) echo '</div>';
关于php - 在 PHP 中输出 MySQL LEFT JOIN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20895657/