2017-04-13 63 views
1

在wordpress中,我试图获取当前行的id和即将到来的行的下一个id。在WordPress的foreach循环中,返回当前行ID和next/prev行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的方式,你只会增加或减少循环数组的键。这是prolly简单的修复。

+0

'的var_dump($项)' - 我猜你有一个数组? – Tom

+0

是的,它是数组 – user1203497

+1

你有没有使用'$ wpdb-> get_results'而不是'WP_Query'或甚至'get_posts'的原因? – Frits

回答

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

?> 
+0

是的,这是有效的。谢谢! – user1203497

+0

+1 - 这几乎就是我想要达到的目标,但是你打败了我。下次可能会输入一点慢一点;)干得好! – Frits