如何在使用PHP / MYSQL循环时检查Next Row的值?

时间:2012-11-08 10:30:12

标签: php

我使用此代码获得了以前的记录

<?php
  $previousRow = array();
  while ($temp = mysql_fetch_row($res2)) 
 {

     echo "<br>currentRow:".$temp[1];
     echo "previousRow:".$previousRow[1];
     $previousRow = $temp; 

  } 
 ?>

oupout

currentRow:1previousRow:

currentRow:5previousRow:1

currentRow:6previousRow:5

currentRow:7previousRow:6

currentRow:8previousRow:7

如何检查上一行替换的下一行的值?

任何帮助都会感激不尽。

3 个答案:

答案 0 :(得分:1)

如果我能帮到你,那么这样的事情会有所帮助吗?

$previousRow = array();
$currentRow = mysql_fetch_row($res2);

while ($currentRow) {
    $nextRow = mysql_fetch_row($res2);

    echo "<br>currentRow:".$currentRow[1];
    echo "previousRow:".$previousRow[1];
    echo "nextRow:".$nextRow[1];

    $previousRow = $currentRow;
    $currentRow = $nextRow;
}

答案 1 :(得分:1)

请尝试以下代码。

$res = array();
while ($result = mysql_fetch_row($r)) {
    $res[] = $result;
 }
 echo "<pre>";
 foreach($res AS $index=>$res1){
     echo "Current".$res1[1]; 
     echo "  Next" . $res[$index+1][1];
     echo "  Prev" . $res[$index-1][1]; echo "<br>";
 }

感谢

答案 2 :(得分:0)

我首先收集所有行,然后使用for:

遍历它们
<?php
$rows = array();
while ($temp = mysql_fetch_row($res2)) 
{
    $rows[] = $temp;
}
$rowCount = count($rows);
for ($i = 0; $i < $rowCount; $i++) {
     echo "<br>currentRow:".$rows[$i][1];
     if ($i > 0) {
         echo "previousRow:".$rows[$i - 1][1];
     }
         if ($i + 1 < $rowCount - 1) {
             echo "nextRow:".$rows[$i + 1][1];
         }
} 
?>