转到此问题的底部以获得答案
我目前正在制作一个表输出,它基本上会逐行列出用户。表输出上的列将由一个特定的SQL列填充,但来自多行(例如John Smith有4行,但该表中每行的X列值不同(。
为了提供更多上下文,这是当前表状态的文本表示。
Name | Col1 | Col2 | Col3
---------------------------------
Name1 | 0 | X | 1
Name2 | 3 | 2 | <--- Value missing
Name3 | 2 | 1 | <--- Value missing (and this continues through the table..
正如您在该表上看到的,第一行填充得很好,但之后的其余行似乎忽略了数据的迭代(因此,为什么其余行只填充2列(
循环的相关代码如下:
while ($row = mysql_fetch_assoc($result)) {
echo "<tr><td>". $row['forename'] . "</td>
<td>". $row['status'] ."</td>";
while ($col = mysql_fetch_assoc($result)) {
if ($col['id'] == $row['id']) {
echo "<td>" . $col['status'] . "</td>";
}
else if ($col['id'] != $row['id']){
echo "</tr>";
break;
}
}
}
有人知道为什么会发生这种情况吗?我希望我已经提供了足够的信息,但如果没有,请告诉我!:(
if ($col['id'] == $row['id'])
{
make a td
}
我认为问题在于有时$col['id']!=$['id']行
通过查看您的代码,我可以建议进行调整。
通过在内部WHILE
循环中调用mysql_fetch_assoc($result)
,可以移动结果对象中的指针(尽管不是有意的(。
您应该使用在第一个循环中检索到的$row
数组。
如果你真的需要像我看到的那样进行比较,你最好的选择是运行整个结果集,首先将单个记录放入一个数组中,然后你可以在循环中使用,如下所示:
$records = array();
//array to hold the retrieved records from the database
while($row = mysql_fetch_assoc($result)){
//loop through the data
$records[] = $row;
}
//continue with your processing, this time using $records as your result set
//an looping through it this time as an array -- you don't need mysql_fetch_assoc
.....
祝你好运!
扩展Okekes的想法(干杯,伙计(我修改了另一种方法,现在效果很好!
//declare new array variable
$resultSet[] = array();
//set offset integer
$i = 0;
//While loop to return all rows from query, and place into multi dimensional array format
while ($row = mysql_fetch_assoc($result)) {
$resultSet[$i] = $row;
$i++;
}
//check that the array isn't empty
if ($resultSet) {
$innerCount = "0";
//count how many rows are in the array
$rowCount = count($resultSet);
//loop through the array, each row, then go through inner loop for columns
for ($row = 0; $row < $rowCount; $row=$row+$numRows) {
//declare variables for the row data
$foreName = $resultSet[$row]['forename'];
$surName = $resultSet[$row]['surname'];
echo "<tr><td>" . $foreName . " " . $surName . "</td>";
for ($col = $row; $col < $rowCount; $col++) {
if ($innerCount < $numRows) {
$innerCount++;
$currStatus = $resultSet[$col]['status'];
echo "<td>" . $currStatus . "</td>";
}
else {
echo "</tr>";
$innerCount = "0";
break;
}
}
}
}