【问题标题】:php MySQL loop within nested divs嵌套div中的php MySQL循环
【发布时间】:2015-10-11 21:57:04
【问题描述】:

我有一个嵌套的 div,我想从我的数据库中获取数据。我在下面解释了我想要的:

<div class="row-fluid">
    <div class="span6">
        **First Entry Here**
    </div>
    <div class="span6">
        **Second Entry Here**
    </div>
</div>
<div class="row-fluid">
    <div class="span6">
        **Third Entry Here**
    </div>
    <div class="span6">
        **FourthEntry Here**
    </div>
</div>

等等……

我现在真的很困惑,解决方案并没有在我的脑海中点击。到目前为止我有这个代码:

$sql = "SELECT * FROM `users`"; 
$result = mysqli_query($conn, $sql);
$ic = 0;
while ($row = mysqli_fetch_assoc($result)) {
if(($ic%2) == 0) {
   $div1 = '<div class="row-fluid">';
   $div2 = '</div>';
}else{
   $div1 = '';
   $div2 = '';
} 
?>

<?=$div1;?>
    <div class="span6">
        <?=$row['userid'];?>
    </div>
<?=$div2;?>

<?php
$ic = $ic + 1;
}
?>

我尝试了两个 while 循环,但它输出了大约 5000 行代码。

【问题讨论】:

  • 该代码会生成什么? span6 = xyzrow-fluid =abcd?
  • 它只是列出了注册用户。 row-fluid 是具有 2 个水平 div (span6) 的行。两个 span6 都包含用户的信息。因此,例如,如果我总共有 10 个用户,那么 row-fluid 应该只生成 5 次,每个 row-fluid 里面应该有 2 个 span6 和用户信息。
  • 它只为我生成 5 个行流体。 eval.in/448721
  • 是的,但结构正在发生变化。 row-fluid 必须在其中包含 2 span6。尝试将输出与我提供的结构相匹配。完全不同。
  • 也就是说row-fluid的子元素必须是span6,span6的父元素必须是row-fluid。 row-fluid 内应该有 2 个 span6。如果您检查输出,第一个 row-fluid 仅包含 1 span6,而下一个 span6 没有 row-fluid,因为它是父元素。我希望我不会混淆这一切。

标签: php mysql loops mysqli nested


【解决方案1】:
$ic = 0;
$temp = "";
while ($row = mysqli_fetch_assoc($result)) {
    $temp .= "<div class='span6'>".$row['user_id']."</div>";
    if ( $ic % 2  != 0 ){
        echo "<div class='row-fluid'>".$temp."<div>";
        $temp = "";
    }
    $ic++;
}
// in case the number of records are odd::
if ($temp != "" )
    echo "<div class='row-fluid'>".$temp."<div>";

【讨论】:

  • 您的逻辑是正确的,但解决方案对我来说并不奏效。尽管我设法通过对其进行了一些修改来使其工作。如果您想发表评论,我会发布它。
【解决方案2】:

@Amr Magdy 的逻辑是正确的,但是解决方案对我来说并不奏效。我现在已经修复它,如果其他人有同样的情况可以参考下面的代码:

<?php
$sql = "SELECT * FROM `users`"; 
$result = mysqli_query($conn, $sql);
$ic = 0;
$temp = "";
while ($row = mysqli_fetch_assoc($result)) {
    $temp = '<div class="span6">'.$row['userid'].'</div>';
    if(($ic%2) == 0) {
       echo '<div class="row-fluid">'.$temp;
    $temp = "";
    }else{
       echo $temp;
    }
    $ic = $ic + 1;
}
echo '</div>';
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 1970-01-01
    • 2013-04-13
    • 2013-11-17
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    相关资源
    最近更新 更多