Split PHP loop into 2 lists

拜拜、爱过 提交于 2020-01-15 10:41:09

问题


I have built the following function, but is it possible to get it to split my lists from one into more so I can have a maximum of 8 <li>'s per <ul>?

function buildProductsMenu($base) {

    $sql = "SELECT *
            FROM tbl_category";
    $result     = dbQuery($sql);
    while ($row = dbFetchAssoc($result)) {
    echo "<ul>";        
        echo "<li class='title'>$row[cat_name]</li>";
            $sqlProd = "SELECT *
                FROM tbl_product WHERE cat_id = $row[cat_id]";
            $resultProd     = dbQuery($sqlProd);
            while ($rowProd = dbFetchAssoc($resultProd)) {
                extract($rowProd);
                echo "<li><a href='".$base."products/".strtolower($row['cat_name'])."/".strtolower($pd_name)."'>".$pd_name."</a></li>";
            }       
    echo "</ul>";               
    }
}

Went with jurgemaister Solution

function buildProductsMenu($base) {

    $sql = "SELECT *
            FROM tbl_category";
    $result     = dbQuery($sql);
    while ($row = dbFetchAssoc($result)) {
        echo "<ul>";        
        echo "<li class='title'>$row[cat_name]</li>";
        $sqlProd = "SELECT * FROM tbl_product WHERE cat_id = $row[cat_id]";
        $resultProd     = dbQuery($sqlProd);
        $counter = 1;
        while ($rowProd = dbFetchAssoc($resultProd)) {
            extract($rowProd);
            if($counter % 12 == 0) {
                $counter = 1;
                echo "</ul><ul style='margin-top:25px;'>";
            }
            echo "<li><a href='".$base."products/".strtolower($row['cat_name'])."/".strtolower($pd_name)."'>".$pd_name."</a></li>";
            $counter++;
        }
        echo "</ul>";
    }
}

回答1:


You can add a counter, and when that counter reaches 8, you start a new ul.

$counter = 1;
while ($rowProd = dbFetchAssoc($resultProd)) {
    extract($rowProd);

    if($counter % 8 == 0) {
        $counter = 1;
        echo "</ul><ul>";
    }

    echo "<li><a href='".$base."products/".strtolower($row['cat_name'])."/".strtolower($pd_name)."'>".$pd_name."</a></li>";
    counter++;
} 



回答2:


Okay, instead of echoing the LIs right from the function I suggest you add them all to an array, once things are in an array, its always easier to manage.

Use array_chunk() on the final array of LIs and it will split it into groups of eight.



来源:https://stackoverflow.com/questions/11308375/split-php-loop-into-2-lists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!