我的数据库中有 67 个类别,我使用 $categories
调用这些类别。
我想将它们全部动态打印到表格中。
到目前为止我已经尝试过:
<table class="mdl-data-table mdl-js-data-table mdl-shadow--2dp">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<?php
$countCat = round(count($categories) / 10); // 67 / 10 = 6. 7 | with round = 7
$i = 0;
foreach ($categories as $key => $value) {
++$i;
if ($i >= 10) {
?>
<td class="mdl-data-table__cell--non-numeric">
<label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect" for="<?php print $value['catID']; ?>">
<input type="checkbox" id="<?php print $value['catID']; ?>" class="mdl-checkbox__input">
<span class="mdl-checkbox__label"><?php print $value['categoryNames']; ?></span>
</label>
</td>
<?php
}
if ($i >= 20) { ?>
<td class="mdl-data-table__cell--non-numeric">
<label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect" for="<?php print $value['catID']; ?>">
<input type="checkbox" id="<?php print $value['catID']; ?>" class="mdl-checkbox__input">
<span class="mdl-checkbox__label"><?php print $value['categoryNames']; ?></span>
</label>
</td>
</tr>
<?php
}
}
?>
</tbody>
即使使用 $i 停止并创建下一行,它也只输出 1 行?
我希望表格有 9 行,并且如果有 67 个或更多类别,它应该自动计算必须创建多少列。
如有任何帮助,我们将不胜感激。
最佳答案
更新2:
使用 $countCat = ceil(count($categories) / 9);
计算您需要多少列。 => N
添加</tr><tr>
标记循环内的每 N 个项目以在 html 表中创建新行。例如,您可以对每 N 个项目使用模 N (% N) 进行存档。
++$i
移动到循环底部,以在末尾递增。
忽略 </tr><tr>
的创建在第一个循环中,您可以使用:&& $i !== 0
<table class="mdl-data-table mdl-js-data-table mdl-shadow--2dp">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<?php
$countCat = ceil(count($categories) / 9);
$i = 0;
foreach ($categories as $key => $value) {
?>
<?php if ($i % $countCat === 0 && $i !== 0) { ?></tr><tr><?php } ?>
<td class="mdl-data-table__cell--non-numeric">
<label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect" for="<?php print $value['catID']; ?>">
<input type="checkbox" id="<?php print $value['catID']; ?>" class="mdl-checkbox__input">
<span class="mdl-checkbox__label"><?php print $value['categoryNames']; ?></span>
</label>
</td>
<?php
++$i;
}
?>
</tr>
</tbody>
结果:
关于php - 表正在创建 1 行而不是创建 9 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53905555/