mysql_fetch_object:获取一个对象和下一个对象?

时间:2011-07-08 07:31:39

标签: php mysql loops

我有一个项目列表,这些是路线的点。这就是我想要实现的目标:

  <ul>
      <li>Point A - Point B</li>
      <li>Point B - Point C</li>
      <li>Point C - Point D</li>
      <li>Point D - Point E</li>
  </ul>

但是我再次知道如何在执行此操作后按顺序获取其中一个:

   while($row=mysql_fetch_object($res)){
     echo'<li>'.$row->title.'</li>';
   }

我可以在同一个循环中得到两个点吗?我应该如何通过它来获得一个点和下一个点? (我的sql查询给了我这样的点数:点A,点B,点C,点D,点E)

2 个答案:

答案 0 :(得分:2)

//Note that this requires at least two rows to work.
//Check with mysql_num_rows before running this if you are unsure.
$first = mysql_fetch_object($res);
$second = mysql_fetch_object($res);

do {

  //do something with the two rows here
  //in your case:
  echo'<li>'. $first->title .' - '. $second->title .'</li>';

  //Move the second row to be the first
  $first = $second;
} while($second = mysql_fetch_object($res));

答案 1 :(得分:0)

  while($row=mysql_fetch_object($res)){
    $myresult[] = $row->title;  
   }

foreach( $myresult as $key=>$value ){

  echo $value->title . ( isset( $myresult[$key+1] ) ? ( '-'. $myresult[$key+1]->title ): '' );

}