我喜欢你的问题,因为我正在处理一个非常相似的情况.由于其他答案有点长,我决定把我的留在这里供你考虑.对我来说,你使用的变量越少,解决方案就越好.
BootstrapContentArranger.PHP
function BootstrapContentArrange($i) {
$items = $i; // qnt of items
$rows = ceil($items/3); // rows to fill
$lr = $items%3; // last row items
$lrc = $lr; // counter to last row
while ($items > 0) { // while still have items
$cell = 0;
if ($rows > 1) { // if not last row...
echo '
while ($cell < 3) { // iterate with 3x4 cols
echo '
$cell++;
}
echo "
$rows--; // end a row
} elseif ($rows == 1 && $lr > 0) { // if last row and still has items
echo '
while ($lrc > 0) { // iterate over qnt of remaining items
$lr == 2 ? // is it two?
print('
print('
$lrc--;
}
echo "
break;
} else { // if round qnt of items (exact multiple of 3)
echo '
while ($cell < 3) { // iterate as usual
echo '
$cell++;
}
echo "
break;
}
$items--; // decrement items until it's over or it breaks
}
}
测试用例
BootstrapContentArrange(3);
BootstrapContentArrange(11);
BootstrapContentArrange(1);
> 3项,输出:
> 11项,产出:
>单个项目,输出:
注意:你可以删除PHP_EOL,我用它来更好地阅读源代码.