php pdo中的类别子类循环

时间:2014-06-13 18:13:51

标签: php html arrays

我有2个表格,其结构和数据如下:

表1

    CREATE TABLE IF NOT EXISTS `category` (
      `category_id` int(5) NOT NULL AUTO_INCREMENT,
      `category_name` varchar(50) COLLATE latin1_general_cs NOT NULL,
      `status` varchar(8) COLLATE latin1_general_cs NOT NULL DEFAULT 'Disabled',
      PRIMARY KEY (`category_id`)
    ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 COLLATE=latin1_general_cs AUTO_INCREMENT=5 ;

有数据:

    INSERT INTO `category` (`category_id`, `category_name`, `status`) VALUES
    (1, 'Electronics', 'Enabled'),
    (2, 'Computers', 'Enabled'),
    (3, 'Cell Phones', 'Enabled'),
    (4, 'Video Games', 'Enabled');

表2

    CREATE TABLE IF NOT EXISTS `subcategory` (
      `subcategory_id` int(5) NOT NULL AUTO_INCREMENT,
      `subcategory_name` varchar(25) COLLATE latin1_general_cs NOT NULL,
      `category_id` int(5) NOT NULL,
      `status` varchar(8) COLLATE latin1_general_cs NOT NULL DEFAULT 'Disabled',
      PRIMARY KEY (`subcategory_id`)
    ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 COLLATE=latin1_general_cs AUTO_INCREMENT=4 ;

有数据:

    INSERT INTO `subcategory` (`subcategory_id`, `subcategory_name`, `category_id`, `status`) VALUES
    (1, 'LED', 1, 'Enabled'),
    (2, 'DVD Players', 1, 'Enabled'),
    (3, 'Tablet', 2, 'Enabled');

我有以下php pdo代码:

    <?php
    include_once 'connstring.inc.php';
    $q = $conn->prepare("SELECT DISTINCT *, C.category_id
    FROM category C LEFT OUTER JOIN subcategory S
    ON C.category_id = S.category_id AND S.status = 'Enabled' 
    WHERE C.status = 'Enabled'
    ");
    $q->execute();   
    //$result = $q->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_GROUP);

    $currentCategory = null;
    while($row = $q->fetch(PDO::FETCH_ASSOC)){
        $categoryID = $row[category_id];
      $categoryName = $row[category_name];
      if ($categoryName != $currentCategory) {
        echo "<h2>".$categoryID.' '.$categoryName."</h2>";
        $currentCategory = $categoryName;
      }
      echo "<p>".$row['subcategory_id'].' '.$row['subcategory_name']."</p>"; 
    }
    ?>

生成类别分组输出为:

 1 Electronics

           1 LED
           2 DVD Players
 2 Computers
            3 Tablet

 3 Cell Phones


 4 Video Games

电子产品和计算机类别有子类别。

我需要生成html标签和css选择器,如下所示:

    <li class='submenu border_t'>
    <div class=cat_bg>
    <a title='Electronics' href='#'><span>Electronics</SPAN></a>
    </div>

    <ul class='level2'>
    <li><a href="#">LED</a></li>
    <li><a href="#">DVD Players</a></li>
    </ul>
    </li>      

    <li class='submenu border_t'>
    <div class=cat_bg>
    <a title='Computers' href='#'><span>Computers</SPAN></a>
    </div>

    <ul class='level2'>
    <li><a href="#">Tablet</a></li>
    </ul>
    </li>  

    <li class='submenu border_t'>
    <div class=cat_bg>
    <a title='Computers' href='#'><span>Cell Phones</SPAN></a>
    </div>

    <li class='submenu border_t'>
    <div class=cat_bg>
    <a title='Computers' href='#'><span>Video Games</SPAN></a>
    </div>

    </ul>
    </div>
    </div>  

这是我写的代码。

<?php
            include_once 'connstring.inc.php';
            //Get records from database
            $q = $conn->prepare("SELECT DISTINCT *, C.category_id
            FROM category C LEFT OUTER JOIN subcategory S
            ON C.category_id = S.category_id AND S.status = 'Enabled' 
            WHERE C.status = 'Enabled'
            ");
            $q->execute();   
            $currentCategory = null;
            ?>
            <div class='categoriesmenuFather ' id='nav-cat' style='display:block' >
            <div class='categories_list categoriesmenu '>
            <ul class='level1'>

            <?php
            while($row = $q->fetch(PDO::FETCH_ASSOC))
            {
            $categoryID = $row[category_id];
            $categoryName = $row[category_name];
            if ($categoryName != $currentCategory) 
            {
            ?>
            <li class='submenu border_t'>
            <div class=cat_bg>
            <a title='<?php echo $categoryName; ?>' href='products.php?catid=<?php echo $categoryID; ?>'><span><?php echo $categoryName; ?></SPAN></a>
            </div>
            <ul class='level2'>
            <?php
            $currentCategory = $categoryName;
              }
            ?>
            <!--BOF Sub-Category-->

            <li><a href="products.php?catid=<?php echo $categoryID.'&subcatid='.$row['subcategory_id']?>"><?php echo $row['subcategory_name']; ?></a></li>
            </ul>
            </li>  
            <!--EOF Sub-Category-->
            <?php
            }
            ?>

            </ul>
            </div>
            </div>  

以上代码会产生意外结果。如何使用查询代码获得上述所需的html格式的结果。请求帮助。

2 个答案:

答案 0 :(得分:0)

"<li class='submenu border_t'><div class=cat_bg><a title='Electronics' href='#'><span>"$categoryName之后添加"</SPAN></a></div>"

如果子类别有,则添加echo "<ul class='level2'>";

然后在"<li><a href=\"#\">"$row['subcategory_name']之前添加"</a></li>"

如果是,则在子类别列表的末尾添加echo "</ul>";

然后echo "</li>";在类别的末尾。

或者简单地在其他文件中使用一些模板,其中包含一些特殊的变量字符串。

答案 1 :(得分:0)

这有点快,又脏。但我认为这是你正在寻找的基本想法。在循环期间,在开始下一个类别之前关闭ul和li。然后,当您完成循环时,您始终可以手动关闭最后一组。

while ($row = $q->fetch(PDO::FETCH_ASSOC)){
    $categoryID = $row['category_id'];
    $categoryName = $row['category_name'];
    if ($categoryName != $currentCategory) {
        $currentCategory = $categoryName;

        //-- Make sure there is html first.
        if ($html) {
            //-- Close the UL from previous category
            if ($previous == true) {
                $html .= '</ul>';
            }
            //-- Close the LI from previous category
            $html .= '</li>';
        }
        //-- Start new category
        $html .= '<li class="submenu border_t">';
        $html .= '  <div class=cat_bg>';
        $html .= '      <a title="'. $categoryName .'" href="#"><span>'. $categoryName .'</span></a>';
        $html .= '  </div>';
        if ($row['subcategory_name']) {
            $html .= '  <ul class="level2">';
            $previous = true;
        }
        else
            $previous = false;
    }

    //-- Add sub category
    if ($row['subcategory_name']) {
        $html .= ' <li><a href="#">'. $row['subcategory_name'] .'</a></li>';
    }
}
//-- Close the last category UL and LI
if ($html) {
    $html .= '  </ul>';
    $html .= '</li>';
}
echo $html;

另一方面,您可能想要从SQL查询中排序结果,以便将类别放在一起。否则,您可能会拆分相同的类别。

编辑:我最后一次更改了代码。我必须设置一个标志$ previous,以确定是否从循环的最后一次迭代中关闭UL。