【问题标题】:Get next value of MySQL statement inside while在while中获取MySQL语句的下一个值
【发布时间】:2011-12-13 17:18:10
【问题描述】:

我正在将一段时间内数据库中的值放入一个数组中。现在我不想检查 - 在 while 内 - 如果下一个 ID 与刚刚输出的相同。如果不是我的想法是将 ID 放在数组中。

有没有可能做到这一点?过一会儿检查查询的下一个输出?

$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"

}

问候

【问题讨论】:

    标签: php mysql arrays while-loop


    【解决方案1】:

    我通常只会将最新的 ID 存储在一个变量中,然后在 while 循环的顶部检查它。在伪代码中,像这样:

    $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
    }
    

    如果您确实需要根据下一个行中发生的情况更改特定行的行为,我建议您在以下中实际影响该更改当您检查新行 ID 与旧行 ID 时,运行循环。

    或者,您可以循环遍历结果集两次:第一次将行放入二维数组,以便您可以轻松地按编号引用差异行。然后第二次,你实际上做了你想做的任何事情,你可以使用[$i + 1]而不是[$i]来引用“下一行”。 (当然,你必须小心最后一行,因为这样偏移量[$i + 1] 不起作用。)

    【讨论】:

    • 我在您的帮助下找到了解决方案。我使用了 array_push 函数。这段代码对我有用: while($row = mysql_fetch_array( $result )) { if($idArr != $row['post_id']){ array_push($basArray[$idArr], $idArr); } $innerArray[$row['meta_key']] = $row['meta_value']; $basArray[$row['post_id']] = $innerArray; $idArr = $row['post_id']; }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多