php - 在 PHP 中输​​出 MySQL LEFT JOIN

标签 php mysql mysqli left-join

我做了这样一个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/

相关文章:

php mysql 在 SELECT 语句中添加 *

php - PHP 中的 mysqli - bind_result 总是返回 null

mysql - 如何在只有一列是查询基础的 MySQL 中进行数据透视

php - 有没有办法在MySQL中获取自动提交的默认值?

php - 查询总是在行数计数上返回 1

PHP num_rows 工作但显示错误

javascript - 工作ajax - 将变量发布到另一个执行的页面中

php - 不再支持 PayPal IPN 和 fsockopen?

mysql - Galera 集群高 Ping

php - 隐藏数据库ID