How to add PHP pagination in array's

后端 未结 2 1655
悲&欢浪女
悲&欢浪女 2020-12-08 11:32

I\'ve been trying a lot of ways to add PHP pagination. I have tried searching and trying to figure other ways of implementing the pagination but none of them work.

H

2条回答
  •  攒了一身酷
    2020-12-08 11:59

    u can use simple PHP function called array_slice()

    $menuItems = array_slice( $menuItems, 0, 10 ); 
    

    show first 10 items.

    $menuItems = array_slice( $menuItems, 10, 10 );
    

    show next 10 items.

    UPDATE:

    $page = ! empty( $_GET['page'] ) ? (int) $_GET['page'] : 1;
    $total = count( $yourDataArray ); //total items in array    
    $limit = 20; //per page    
    $totalPages = ceil( $total/ $limit ); //calculate total pages
    $page = max($page, 1); //get 1 page when $_GET['page'] <= 0
    $page = min($page, $totalPages); //get last page when $_GET['page'] > $totalPages
    $offset = ($page - 1) * $limit;
    if( $offset < 0 ) $offset = 0;
    
    $yourDataArray = array_slice( $yourDataArray, $offset, $limit );
    

    UPDATE#2:

    Example of pagination:

    $link = 'index.php?page=%d';
    $pagerContainer = '
    '; if( $totalPages != 0 ) { if( $page == 1 ) { $pagerContainer .= ''; } else { $pagerContainer .= sprintf( ' « prev page', $page - 1 ); } $pagerContainer .= ' page ' . $page . ' from ' . $totalPages . ''; if( $page == $totalPages ) { $pagerContainer .= ''; } else { $pagerContainer .= sprintf( ' next page » ', $page + 1 ); } } $pagerContainer .= '
    '; echo $pagerContainer;

提交回复
热议问题