【问题标题】:Php mysql arrange html output three by threephp mysql 将 html 输出三排三排
【发布时间】:2015-10-21 06:53:05
【问题描述】:

它可能看起来很简单,但现在让我很头疼。

<?php

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

这是我想要实现的输出:

<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>

基本上每3个元素都要封装在自己的div中。

这样做的方法是什么?

【问题讨论】:

    标签: php html mysql


    【解决方案1】:

    我认为您正在寻找与此类似的算法。它将在1 添加一个打开的&lt;div&gt; 并在3 关闭&lt;div&gt;。您将不得不容纳留下余数的数字:

    // 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++;
    }
    

    随机数会给你类似的东西:

    <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>
    

    这是另一个例子:Displaying data from arrays in a dynamic table PHP

    您也可以执行类似的array_chunk()。在这种情况下,您不需要任何计算来适应余数:

    // 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>";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-12
      • 1970-01-01
      • 1970-01-01
      • 2014-10-17
      • 2013-07-09
      • 1970-01-01
      • 2020-09-14
      相关资源
      最近更新 更多