我正在使用此代码根据数据库中的值生成行,我敢肯定有一种更有效的方法可以做到这一点,但我不确定如何做!

if ($empty == 1) {
    echo "<li class='col-sm-4'><div class='horse-wrap empty'>Empty</div></li>";
}
if ($empty == 2) {
    echo "<li class='col-sm-4'><div class='horse-wrap empty'>Empty</div></li>";
    echo "<li class='col-sm-4'><div class='horse-wrap empty'>Empty</div></li>";
}
if ($empty == 3) {
    echo "<li class='col-sm-4'><div class='horse-wrap empty'>Empty</div></li>";
    echo "<li class='col-sm-4'><div class='horse-wrap empty'>Empty</div></li>";
    echo "<li class='col-sm-4'><div class='horse-wrap empty'>Empty</div></li>";
}
if ($empty == 4) {
    echo "<li class='col-sm-4'><div class='horse-wrap empty'>Empty</div></li>";
    echo "<li class='col-sm-4'><div class='horse-wrap empty'>Empty</div></li>";
    echo "<li class='col-sm-4'><div class='horse-wrap empty'>Empty</div></li>";
    echo "<li class='col-sm-4'><div class='horse-wrap empty'>Empty</div></li>";
}

最佳答案

您可以使用for循环来做到这一点:

$empty = 5;
$str = '';
for(i=0;$i<$empty;$i++) {
    $str .= "<li class='col-sm-4'><div class='horse-wrap empty'>Empty</div></li>";
}
echo $str;

关于php - 有没有更好的方法在 PHP 中做到这一点,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37255323/

10-15 09:57