douqiao1997 2015-01-29 13:05
浏览 599
已采纳

如何对foreach循环进行分页?

I have this foreach loop wich shows the supporters located in the post_meta from a custom post type. What I want to do is add pagination to the foreach loop. I have already found a way to decide how many supporters are shown by slicing the array, but now I am at a loss. And have no idea how to proceed.

Function to get the supporters array

function getSupporters($petitieID){
$support = get_post_meta(get_the_ID(), 'supporters', true);

if (!empty($support)){
    return $support;
}}

Function to show the individual supporters in the array

function showSupporters($petitieID){

$supporters = getSupporters($petitieID);
if (!empty($supporters)){
    foreach (array_slice($supporters, 0, 2) as $supporter){

    $supporterID = $supporter->post_author;
        the_author_meta('first_name', $supporterID);
    }

}else {

    echo    'no votes';
}
}
  • 写回答

1条回答 默认 最新

  • duanniesui6391 2015-01-29 13:23
    关注

    You could determine which page is currently shown in a GET variable in your address

    .../supporters.php?page=1
    

    Then you could set the offset of your array_slice function accordingly

    $nItemsPerPage = 2;
    $page = isset($_GET['page'])?$_GET['page']:1;
    array_slice($supporters, $nItemsPerPage*($page-1), $nItemsPerPage)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 chaquopy python 安卓
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题