我有一个包含24项的php关联数组。我想循环遍历它们并打印4行,每行有6列。
如何实现这一目标?
答案 0 :(得分:1)
这应该适合你:
(作为一个例子,我使用带数字的数组并添加了密钥)
<?php
$array = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24);
$count = 1;
foreach($array as $k => $v) {
echo sprintf(" Key: %3d Value %3d", $k, $v);
if($count % 6 == 0)
echo "<br />";
$count++;
}
?>
输出:
Key: 0 Value 1 Key: 1 Value 2 Key: 2 Value 3 Key: 3 Value 4 Key: 4 Value 5 Key: 5 Value 6
Key: 6 Value 7 Key: 7 Value 8 Key: 8 Value 9 Key: 9 Value 10 Key: 10 Value 11 Key: 11 Value 12
Key: 12 Value 13 Key: 13 Value 14 Key: 14 Value 15 Key: 15 Value 16 Key: 16 Value 17 Key: 17 Value 18
Key: 18 Value 19 Key: 19 Value 20 Key: 20 Value 21 Key: 21 Value 22 Key: 22 Value 23 Key: 23 Value 24
答案 1 :(得分:0)
这样的事情可以解决问题:
$columns = 6;
$count = $columns;
foreach ($array as $k=>$v) {
print $v.", ";
$count--;
if (!$count) {
print "<br/>";
$count = $columns;
}
}