在查询

时间:2016-01-04 10:32:58

标签: php arrays mysqli foreach

我想用一个类来扭曲每两行。所以我从这里看到了一些指导和谷歌搜索,并找到foreach array_chunk来做到这一点。我尝试如下,不能显示任何结果。没有预先做好其工作。我的错了吗?

enter image description here

在上面的图片中,我想做;我的每两个类别都有一个类。并在每个顶级类别后添加分隔符。

这是我的尝试:

echo '<ul class="dropdown-menu dropdown-menu-large row">';
    $sql = "SELECT id,name FROM main_cata ORDER BY id ASC";
    $execute = $dbh->query("$sql");
    $rowcount = $execute->num_rows ;
    $row = $dbh->query($sql) ; 

    while ($row = $execute->fetch_assoc()) {

         foreach (array_chunk($row, 2, true) as $array){
             echo'<li class="col-sm-3">';

             foreach($array as $rows){
                  echo '<ul><li class="dropdown-header">'.$rows->name.'</li>';

                  $sql2 = "SELECT id,name,page FROM catagory WHERE m_cata = '".$rows->id."' ORDER BY id ASC";
                  $execute2 = $dbh->query("$sql2");
                  $rowcount2 = $execute2->num_rows ;
                  $row = $dbh->query($sql) ; 
                  while ($row = $execute2->fetch_assoc()) {
                  $cid = $row['id'];
                  $cname = $row['name'];    
                  $page = $row['page'];
                  echo '<li><a href="#">'.$cname.'</a></li>';
                  }
                  echo '<li class="divider"></li></ul>';
              }
              echo '</li>'; 
         }       
    }
echo '</ul>';

1 个答案:

答案 0 :(得分:0)

while ($row = $execute->fetch_assoc()) {

fetch_assoc 从查询返回1行(id,name),然后你使用结果并拆分为2(https://secure.php.net/manual/pt_BR/mysqli-result.fetch-assoc.php),你可以做的是,做一个计数器而不是每次达到2时重置的数组块。

foreach (array_chunk($row, 2, true) as $array){

$ row的内容例如是数组(&#39; id&#39; =&gt; 1,&#39; name&#39; =&gt;&#39;类别1&#39;)。

foreach($array as $rows){

您无需再次迭代。

简单版本:

counter = 0;
echo "<ul>";
while (row = execute->fetch_assoc()) {
     if (counter == 0) {
        echo "init li";
     }

    echo "subinit li";
    get subcategories
    while (row2 = execute2->fetch_assoc()) {
         print content
    }
    echo "subend li";    

    if (counter == 2) {
        counter == 0;
        echo "end li";
    } else {
        counter++;
        echo "divider";
    }
}
echo "</ul>";