dougou8573 2015-10-20 21:10
浏览 54
已采纳

Php mysql三个一个地排列html输出

It may be looking pretty simple but it gives me headaches right now.

<?php

$sql = DB::query("SELECT `post_id` FROM `table` LIMIT 0,9");
foreach ($sql as $row){ 
$id = $row["post_id"];
}

And this is the output that i want to achieve:

<div class="row">
<li>1</li>
<li>2</li>
<li>3</li>
</div>
<div class="row">
<li>4</li>
<li>5</li>
<li>6</li>
</div>
<div class="row">
<li>7</li>
<li>8</li>
<li>9</li>
</div>

Basically, every 3 elements to be encapsulated in their own div.

What is the way to do this?

  • 写回答

1条回答 默认 最新

  • dqsk4643 2015-10-20 22:27
    关注

    I think you are looking for an algorithm similar to this. It will add an open <div> at 1 and close <div> at 3. You would have to accommodate for numbers that leave a remainder:

    // Set the start at 1
    $i = 1;
    foreach ($sql as $row){
        // If the loop hits 1, add <div>
        if($i == 1)
            echo '<div>'.PHP_EOL;
        echo $id = "\t<li>".$row["post_id"].'</li>'.PHP_EOL;
        // If the loop hits 3, add </div>
        if($i == 3) {
            echo '</div>'.PHP_EOL;
            // Reset the counter
            $i = 0;
        }
        // Increment up
        $i++;
    }
    

    With random numbers will give you something like:

    <div>
            <li>309781723</li>
            <li>1591425966</li>
            <li>1922824365</li>
    </div>
    <div>
            <li>1861766038</li>
            <li>2065624155</li>
            <li>504061231</li>
    </div>
    <div>
            <li>143488299</li>
            <li>806735480</li>
            <li>605627018</li>
    </div>
    <div>
            <li>1305718337</li>
            <li>2080669131</li>
            <li>314748482</li>
    </div>
    

    Here is another example: Displaying data from arrays in a dynamic table PHP

    You can also do an array_chunk() similar to this. You don't need any calculations to accommodate for remainders in this scenario:

    // Split into sets of 3
    $arr    =   array_chunk($sql,3);
    $a = 0;
    // You could probably do an array_map() but I am not experienced enough
    // with array_map() to do it efficiently...or even at all, to be perfectly honest
    foreach($arr as $row) {
            for($i = 0; $i < count($row); $i++)
                $new[$a][]  =   $row[$i]['post_id'];
            // Assemble the rows via implode
            $nRow[] =   "\t<li>".implode("</li>".PHP_EOL."\t<li>",$new[$a])."</li>".PHP_EOL;
    
            $a++;
        }
    // Implode with <div> wrappers
    echo "<div>".PHP_EOL.implode("</div>".PHP_EOL."<div>".PHP_EOL,$nRow)."</div>";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器