dongmanzui8486 2011-10-23 20:47
浏览 36

在里面获取MySQL语句的下一个值

I'm putting values from the database inside a while into an array. Now I wan't to check - inside the while - if the next ID is the same as just outputed. If it isn't my thought is to put the ID inside the array.

Is there any possibility to do this? To check a the next output of a query in a while?

$result = mysql_query("SELECT * FROM $postmeta ORDER BY post_id ASC") 
or die(mysql_error());

$basArray = array();    

while($row = mysql_fetch_array( $result )) {

    $innerArray[$row['meta_key']] = $row['meta_value'];     
    $basArray[$row['post_id']] = $innerArray;
// Above post_id I want to check if it is the same as the "next coming"

}

Greetings

  • 写回答

1条回答 默认 最新

  • dongyan6235 2011-10-23 20:53
    关注

    I would usually just store the most recent ID in a variable, and check it at the top of the while loop. In pseudocode, like this:

    $old_row_id = -1; // any value that can't legitimately appear
    while ($row = fetch_array($result)) {
        if ($old_row_id == $row['id']) {
            // logic to follow if IDs are the same
        } else {
            // logic to follow if IDs are different
        }
        // logic to follow in either case, if any
        $old_row_id = $row['id']; // update variable for the next run through
    }
    

    If you really do need to change the behaviour for a particular row according to what happens in the next row, I recommend that you actually effect that change in the following run through the loop, when you check the new row ID against the old one.

    Alternatively, you can loop through the resultset twice: the first time putting the rows into a 2-dimensional array so that you can easily reference difference rows by number. Then the second time, you actually do whatever you wanted to do in the first place, and you can reference "the next row" by using [$i + 1] rather than [$i]. (Of course then you have to be careful about the final row, because then the offset [$i + 1] doesn't work.)

    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀