user1203497 user1203497 - 6 months ago 37
PHP Question

In wordpress foreach loop, return current row id and next/prev row id

In wordpress, I am trying to get current id of a row and a next id of upcoming row.

Example database:

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


code:

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


I think in none Wordpress way you would just increase or decrease array key in loop. It is prolly simple fix.

Answer Source

You could use something like the following:

<?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;
    }
}

?>