douqiao1997
douqiao1997
2015-01-29 13:05

如何对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 duanniesui6391 6年前

    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)
    
    点赞 评论 复制链接分享