我试图让数据显示在两个表行而不是一行。这是我目前的代码:
<tr>
<th>Title</th>
<th>Body</th>
<th>Date Posted</th>
</tr>
<tr>
<?php
for ($i=0; $i<count($entries); $i++) {
echo "<td>" . $entries[$i] . "</td>";
}
?>
</tr>
如果我尝试在echo语句中回显表行标记,则它与表标题值不匹配。
由于
(我的问题http://imgur.com/O15fqHd的截图)
答案 0 :(得分:1)
每个条目是数组中的PER行。每个项目都可以包含这些字段。所以,你可以这样做:
// process each row
foreach ($entries as $row) {
echo '<tr>';
// now process each column
foreach ($row as $fieldname => $value) {
echo '<td>'.$value.'</td>';
}
echo '</tr>';
}
结果如下:
<tr>
<td>value row 1 col 1</td>
<td>value row 1 col 2</td>
<td>value row 1 col 3</td>
</tr>
<tr>
<td>value row 2 col 1</td>
<td>value row 2 col 2</td>
<td>value row 2 col 3</td>
</tr>
<tr>
<td>value row 3 col 1</td>
<td>value row 3 col 2</td>
<td>value row 3 col 3</td>
</tr>
<tr>
<td>value row 4 col 1</td>
<td>value row 4 col 2</td>
<td>value row 4 col 3</td>
</tr>
....
如果这对您不起作用,也许您可以在data
变量中添加一个示例$entries
。
您评论中的数据如下所示:
array(6) {
[0]=> string(9) "Test Post"
[1]=> string(59) "Test post to see if this will work in the edit post section"
[2]=> string(10) "2014-07-03"
[3]=> string(11) "Test Post 2"
[4]=> string(81) "I sure hope this array return displays all instead of just one, we will find out." [5]=> string(10) "2014-07-03"
}
应该是这样的:
Array
(
[0] => Array
(
[0] => "Test Post"
[1] => "Test post to see if this will work in the edit post section"
[2] => "2014-07-03"
)
[1] => Array
(
[0] => "Test Post 2"
[1] => "I sure hope this array return displays all instead of just one, we will find out."
[2] => "2014-07-03"
)
)
现在,检查一下获取数据的方式并构建类似的东西。如果您使用的是MySQL
,请尝试我的包装类:https://github.com/lodev09/php-mysqli-wrapper-class
答案 1 :(得分:0)
如果你只想使用一个循环(尽管它会带来所有糟糕的编程实践),你可以试试这个:
$numberOfTableColumns = 3;
$entries = ...;
$j = 0;
for ($i=1; $i<=count($entries); $i++) {
if ($i % $numberOfTableColumns != 0){
if ($i == 1){
echo "<tr>";
}
if ($j == 1){
$j = 0;
echo "<tr>";
}
}
echo "<td>" . $entries[$i-1] . "</td>";
if ($i % $numberOfTableColumns == 0){
$j = 1;
echo "</tr>";
}
}
但是,必须承认lodev09的解决方案更加优雅。