1

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.

user1203497
  • 507
  • 3
  • 11
  • 18

1 Answers1

2

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

?>
Sebastian
  • 526
  • 2
  • 15
  • +1 - this is almost exactly what I wanted to achieve, but you beat me to it. Type a little slower next time maybe ;) good job! – Frits Apr 13 '17 at 10:02