2015-10-20 11 views
0

它可能看起來很簡單,但它現在讓我頭疼。Php mysql安排html輸出三個三個

<?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封裝。

這樣做的方法是什麼?

回答

1

我想你正在尋找一個類似這樣的算法。它將增加一個開放的<div>1並關閉<div>3。你將不得不適應該留餘數:

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