如何在while循环中创建更多列?

时间:2015-09-11 13:39:20

标签: php

我有这段代码

while ($row = mysqli_fetch_array ($r, MYSQLI_ASSOC)) {

        echo "
        <div><h4><a href=\"page.php?id={$row['subcategory_id']}\">{$row['subcategory']}</a></h4>
        </div>\n";

    }

有了这个,我在页面上放了一个带有子类别的垂直线。例如:

foo
foo
foo
foo
foo
foo
foo

我想将这些子类别限制为10,并在每个10之后再次从顶部开始,如下所示:

foo foo foo
foo foo foo
foo foo foo
foo foo foo
foo foo foo
foo foo foo
foo foo foo

有人可以告诉你怎么做吗?

1 个答案:

答案 0 :(得分:0)

以下是一个有效的例子:https://3v4l.org/MmWJA

以下是使用您自己的代码的示例:

// get your array in a var
$array = mysqli_fetch_all($r, MYSQLI_ASSOC);

// set column to 10 items tall
$col_height = 10; 

// count the array
$count = count($array);

// determine number of columns based on column height and array size
$row_len = $count / $col_height;

//create iterator
$i = 0;

// loop that shits
foreach($array as $row) {

    // added display = inline 
    echo "<div style='display:inline-block;'><h4><a href=\"page.php?id={$row['subcategory_id']}\">{$row['subcategory']}</a></h4></div>\n";

    // echo a line break only when needed, reset the iterator
    if($i == $row_len){
        echo "<br>";
        $i = 0;
    }
}