在wordpress foreach循环中,返回当前行id和next / prev row id

时间:2017-04-13 09:35:53

标签: php wordpress loops

在wordpress中,我试图得到一行的当前id和即将到来的行的下一个id。

示例数据库:

    -----------------------------
    |   id  |   book  | orderby |
    -----------------------------
    |    3  |    b    |     1   |
    -----------------------------
    |    1  |    f    |     2   |
    -----------------------------
    |    2  |    g    |     3   |
    -----------------------------

代码:

$entries = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."_books" ORDER BY orderby ASC );
foreach ( $entries as $print ){
    $prev = //on second row this would be 3
    $current = $print->id  //on second row this would be 1
    $next =  //on second row this would be 2
}

我认为在任何Wordpress方式中你都不会增加或减少循环中的数组键。这是一个非常简单的修复。

1 个答案:

答案 0 :(得分:2)

您可以使用以下内容:

<?php

$entries = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."_books ORDER BY orderby ASC");
$entries = array_values($entries); //shouldn't be needed, but used just in case wordpress returns a non-incrementing key structure for whatever reason

foreach ($entries as $k=>$v) {
    if (isset($entries[$k - 1])) {
        $prev = $entries[$k - 1]->id;
    }
    else {
        $prev = null;
    }

    $current = $v->id;

    if (isset($entries[$k + 1])) {
        $next = $entries[$k + 1]->id;
    }
    else {
        $next = null;
    }
}

?>