2011-05-15 51 views
2

我不明白這一點。我需要解決看似簡單的問題,但它超出了我的邏輯。我需要編寫一個函數:table_columns($輸入,$的cols),這將輸出一個表(例如):從PHP陣列生成HTML表

$input = array('apple', 'orange', 'monkey', 'potato', 'cheese', 'badger', 'turnip'); 
$cols = 2; 

預期輸出:

<table> 
    <tr> 
    <td>apple</td> 
    <td>cheese</td> 
    </tr> 
    <tr> 
    <td>orange</td> 
    <td>badger</td> 
    </tr> 
    <tr> 
    <td>monkey</td> 
    <td>turnip</td> 
    </tr> 
    <tr> 
    <td>potato</td> 
    <td></td> 
    </tr> 
</table> 

回答

6

想想看這樣的。假設你有一個項目一個這樣的數組:

a, b, c, d, e, f, g, h, i, j, k 

設置爲2列,你需要使它們順序如下:

a g 
b h   0 6 1 7 2 8 3 9 4 10 5 
c i  ---> a g b h c i d j e k f 
d j 
e k 
f 

有三列:

a e i 
b f j  0 4 8 1 5 9 2 6 10 3 7 
c g k ---> a e i b f j c g k d h 
d h 

所以,大致如下:

function cells ($input, $cols) { 

    $num = count($input); 
    $perColumn = ceil($num/$cols); 

    for ($i = 0; $i < $perColumn; $i++) { 

    echo "<tr>"; 

    for ($j = 0; $j < $cols; $j++) { 
     // you'll need to put a check to see you haven't gone past the 
     // end of the array here... 

     echo "<td>" . $input[$j * $perColumn + $i] . "</td>"; 
    } 
    echo "</tr>"; 
    } 
} 
+0

謝謝,這正是我所需要的 – Caballero 2011-05-15 18:06:41

-1

試試這個功能:

function table_columns($input, $cols) 
{ 
    int $i = 0; 
    echo "<table><tr>"; 
    foreach ($input as $cell) 
    { 
     echo "<td>".$cell."</td>"; 
     $i++; 
     if($i == $cols) 
     { 
      $i = 0; 
      echo "</tr><tr>"; 
     } 
    } 
    echo "</tr></table>"; 
} 

我希望它能解決您的問題。

[編輯:修正了錯誤,很着急]

+0

You'r關閉表格標籤應該在foreach循環之外。你也不會處理計數($ input)%$ cols!= 0的情況。 – 2011-05-15 17:53:25

+0

這不起作用,我需要類似於例子中的輸出 – Caballero 2011-05-15 17:54:35

+0

你忘了增加$ i嗎? – Sylverdrag 2011-05-15 18:02:22

4
$input = array_chunk($input, $cols); 
$html = '<table>'; 
foreach($input as $tr){ 
    html .= '<tr>'; 
    for($i = 0; $i < $cols; $i++) $html .= '<td>'.(isset($tr[$i]) ? $tr[$i] : '').'</td>'; 
    $html .= '</tr>'; 
} 
$html .= '</table>'; 
+0

這個不起作用的原因,它只能配對每兩個元素,這不是我所需要的... – Caballero 2011-05-15 17:55:18