我有一个数据数组,我希望在一个动态表中显示,但需要垂直。
目前我得到以下输出:
示例1:
1 - 2 - 3 - 4
5 - 6 - 7 - 8
9 - ... etc.
但我需要这样:
示例2:
1 - 4 - 7
2 - 5 - 8
3 - 6 - 9
我搜索了Google和on stack,但找不到一个直接的答案,我可以用它来解决我的问题。
$array = array("4|Four","12|Twelve","2|Two","5|Five","11|Eleven","3|Three","1|One","6|Six","10|Ten","8|Eight","7|Seven","9|Nine");
$maxcols = 3;
$i = 0;
$table = "<table width='"80%'" border='"0'">'n";
$table .= "<tr>'n";
if(!empty($array))
{
rsort($array,SORT_NUMERIC);
for($p=0;$p<sizeof($array);$p++)
{
list($num,$title) = explode("|", trim($array[$p]));
if ($i == $maxcols)
{
$i = 0;
$table .= "</tr>'n<tr>'n";
}
$table .= "<td>"."[ ".$num." ]"." ".$title."</td>'n";
$i++;
}
while ($i < $maxcols)
{
$table .= "<td> </td>'n";
$i++;
}
$table .= "</tr>'n";
$table .= "</table>'n";
}
echo $table;
上面的代码输出如第一个示例所示,但我不能让我的头在第二个示例中看到它的输出。
我最初想使用array_chunk将数组分解成行,但后来我想到,只使用数学也可以做到这一点。
$rows = 3; // define how many rows as you want
$array = array("4|Four","12|Twelve","2|Two","5|Five","11|Eleven","3|Three","1|One",
"6|Six","10|Ten","8|Eight","7|Seven","9|Nine");
rsort($array,SORT_NUMERIC);
// determine number of columns needed to fit the values into the number of rows you want
$columns = count($array) / $rows;
$table = '<table width="80%" border="0">';
for ($i=0; $i < $rows; $i++) {
$table .= '<tr>';
for ($j=0; $j < $columns; $j++) {
$index = (int) ($j * $rows + $i); // Do the math to get the proper array index
if (isset($array[$index])) {
list($num,$title) = explode("|", trim($array[$index]));
$table .= "<td>"."[ ".$num." ]"." ".$title."</td>'n";
} else {
$table .= '<td> </td>';
}
}
$table .= '</tr>';
}
$table .= '</table>';
上面的例子产生了一个这样的网格,其中的数字是数组键。
0 3 6 9
1 4 7 10
2 5 8 11
生成这个带有两个for循环的网格的数学方法是这样的:
0*3+0 1*3+0 2*3+0 3*3+0
0*3+1 1*3+1 2*3+1 3*3+1
0*3+2 1*3+2 2*3+2 3*3+2
或(列索引*总行数)+行索引。无论您是指定行数还是列数,嵌套循环部分都将保持不变。唯一需要更改的是开始计算指定数量的列需要多少行或反之亦然的数学方法。如果将开头部分改为
$columns = 3;
$rows = ceil(count($array) / $columns);
那么您应该能够指定列数而不是行数。ceil
是必要的,因为除法的任何余数都必须四舍五入才能得到所需的总行数。我认为这就是为什么你得到重复的值,当你第一次切换行和列。
我是这样做的。
<table align="center" style="width:40%;">
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
<?
$rotate = 0;
$amount = 1;
while($amount <= 50)
{
if($rotate == 0) {
echo '<tr>
<td>test</td>';
$rotate = 1;
}
else if($rotate == 1) {
echo '<td>test2</td>';
$rotate = 2;
}
else if($rotate == 2) {
echo '<td>test3</td>';
$rotate = 0;
echo '</tr>';
}
$amount++;
}
echo '</tr></table>';
这将在一个空白的php页面上工作-所以你可以看到它是如何工作的。
为了进一步扩展@DontPanic的回答,可以将转换数组键的问题抽象为可以有任意数量的列。两种实现基本上是等价的。
// returns a closure that can be used to translate the index order
function getIndexTranslator($list, $numColumns) {
$numRows = ceil(count($list)/$numColumns);
return function($x) use ($list, $numColumns, $numRows){
return ($x % $numColumns) * $numRows + floor($x / $numColumns);
};
}
然后,您可以使用返回的函数来允许您按照所需的文档顺序遍历元素。下面是你如何使用上面的函数:
$transformer = getIndexTranslator($arr, 3);
for($x = 0; $x < count($arr); $x++){
echo $arr[$transformer($x)], $x % 3 == 2?"'n":" ";
}
在这里设置一下