从PHP数组生成HTML表 [英] Generating HTML table from PHP array
本文介绍了从PHP数组生成HTML表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不明白这一点.我需要解决看似简单的问题,但这超出了我的逻辑.我需要编写一个函数:table_columns($ input,$ cols),该函数将输出一个表(示例):
I don't understand this. I need to solve seemingly simple problem, and yet it's beyond my logic. I need to write a function: table_columns($input, $cols) which would output a table(example):
$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>
推荐答案
这样思考.假设您有一系列这样的项目:
Think about it like this. Say you have an array of items like this:
a, b, c, d, e, f, g, h, i, j, k
将列设置为 2
时,您需要按以下顺序呈现它们:
With columns set to 2
, you'd need to render them in this order:
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>";
}
}
这篇关于从PHP数组生成HTML表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文