2014-01-11 26 views
0

我正在製作一個函數,其中我試圖獲取的數據來自two columnsone row,並且生成了多行。數據安排在表格中,我試圖用three columns而不是two來製作表格,但它沒有解決。有時在某些行中,它會跳過一列,有時會在一行中輸出完美的3列。下面的代碼適用於每行中的two columns。但是如何使數據在一行中出現在three column從後端獲取數據到一行中的三列

$r = 1; 
$html = ""; 
$html .= '<table class="table table-bordered"> 
<tbody><tr>'; 
    foreach($products as $pr) { 
     if($r != 1) {$rw = (bool)($r & 1); 
     $html .= $rw ? '</tr><tr>' : ''; } 
      $html .= '<td><strong>'.$pr->name.'</strong><br>'.'<strong>Rs '.$pr->price.'</strong><br>'.$this->product_barcode($pr->code, 30, 147).'</td>'; 
     $r++; 
    } 
$html .= '</tr></tbody> 
</table>'; 

$data['html'] = $html; 

這裏是輸出截圖。它在一行中排成兩列。我想要一列3列。

See its coming in 2 columns i want this in 3

回答

2

在這裏你去:)模運算符可以幫助這裏。

http://en.wikipedia.org/wiki/Modulo_operation

$html = '<table class="table table-bordered"><table>'; 
$r = 0; 
$columns = 3; 
foreach ($products as $pr) { 
    if ($r%$columns == 0) $html .= '<tr>'; 
    $html .= '<td>'; 
    $html .= '<strong>'.$pr->name.'</strong><br />'; 
    $html .= $pr->price.'<br />'; 
    $html .= $this->product_barcode($pr->code, 30, 147); 
    $html .= '</td>'; 
    if ($r%$columns == $columns || $r++ == count($products)-1) $html .= '</tr>'; 
} 
$html .= '</tbody></table>'; 
+0

很抱歉,但所有這些值(名稱,價格,條形碼)的將是一個​​會有3​​一行又會有很多行。我能夠在排隊中解決2​​但不是3 – user1001176

+0

對不起 - 我發現很難明確你的意思。你能否提供你的$ products數組的var_dump? –

+0

1分鐘我會上傳屏幕截圖 – user1001176