2011-05-24 71 views
1

我有一個數組,我想將其轉儲到一個表中,但是有一個新的X列項。例如:將數組轉換成表

item 1 |項目2 |項目3 |項目4 |

item 5 |項目6 |項目7 |項目8 |

item 9 |等等...

我已經可以讓一定數目的項目後添加一個新的列(在這種情況下,4)使用此代碼:

$input = array('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'); 

$cols = 4; 

echo "<table border=\"5\" cellpadding=\"10\">"; 

for ($i=0; $i < count($input); $i++) 
{ 
echo "<tr>"; 
    for ($c=0; $c<$cols; $c++) 
    { 
    $n = $i+$c; 
    echo "<td>$input[$n]</td>"; 
    } 
echo "</tr>"; 
$i += $c; 
} 

echo "</table>"; 

但由於某些原因,一個接列以'四'結尾,下一個以'六'開始。

+0

這是因爲你正在重置'$ i'在循環內,然後'for()'本身會執行'$ i ++'。 Yuu應該在頂部或'$ i + = $ c - 1;'底部 – 2011-05-24 20:32:40

回答

3

陣列功能可以說是相當神奇:

$input = array('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'); 
$cols = 4; 
$table = array_chunk($input, $cols); 

echo "<table border=\"5\" cellpadding=\"10\">"; 

foreach($table as $row) { 
    echo "<tr>"; 
    foreach($row as $cell) { 
     echo "<td>$cell</td>"; 
    } 
    echo "</tr>"; 
} 
echo "</table>"; 

裁判:http://php.net/manual/en/function.array-chunk.php

+1

處爲$($ i ...; $ i + = $ c)'我認爲$ rows,$ row,$ cell會導致未定義的變量消息錯誤。 – SIFE 2011-05-24 20:33:36

+1

@SIFE我認爲他的意思是$ table而不是$ rows。我改變了它,現在它工作正常。 – Preston 2011-05-24 20:34:39

+0

@Preston是的,我決定我不喜歡$行,但沒有完全做,thx爲編輯。 – Kai 2011-05-24 20:39:50

0
$input = array('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'); 

$cols = 4; 

echo "<table border=\"5\" cellpadding=\"10\">"; 

for ($i=0; $i < count($input); $i++) 
{ 
echo "<tr>"; 
    for ($c=0; $c<$cols; $c++) 
    { 
    $n = $i+$c; 
    echo "<td>$input[$n]</td>"; 
    } 
echo "</tr>"; 
$i += $c - 1; 
} 

echo "</table>"; 

凱的答案是一個更好的解決方案。我所做的只是從$i += $c一行中減去1。

0

由於當您檢測到需要執行新行時,您正在使用for循環增加計數器的額外時間,因此您每5秒跳過一次。

這裏是另一個appraoch:

$ary = array('item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8'); 


echo "<table><tr>"; 
foreach($ary as $k => $item) 
{ 
    if($k % 4 == 0 && $k != 0) 
     echo "</tr><tr>"; 
    echo "<td>$item</td>"; 
} 
echo "</tr></table>"; 
1

關於第一個循環$我將$ C(這將永遠是3)遞增。然後for循環會將$ i值增加一個($ i ++),這將使其跳過'五'。

您可以控制增量或讓for循環控制它。

0

如果你瞭解清楚了,你想你傾倒在指定的行數的數組:

for ($i=0; $i < count($input); $i++) 
{ 
echo "<tr>"; 
    for ($c=0; $c<$cols; $c++) 
    { 
    echo "<td>$input[$i]</td>"; 
    } 
echo "</tr>"; 
} 
0

如果您想保留原來的邏輯,改變$i的增量$i += (c$-1)因爲你除了列寬以外,循環中還會增加$i。然後也迎合空值。這將工作:

<?php 
$input = array('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',  'ten'); 

$cols = 4; 

echo "<table border=\"5\" cellpadding=\"10\">" . PHP_EOL; 

for ($i=0; $i < count($input); $i++) 
{ 
echo "<tr>"; 
    for ($c=0; $c<$cols; $c++) 
    { 
    $n = $i+$c; 
    if ($n < count($input)) 
     echo "<td>$input[$n]</td>" . PHP_EOL; 
    else 
     echo "<td></td>" . PHP_EOL; 
    } 
echo "</tr>"; 
$i += ($c-1); 
} 

echo "</table>"; 
?>