Paginate result of foreach loop with php

问题: UPDATE***I am attempting to paginate the result of this foreach loop. This ALMOST works. Im able to get all of the information I need to paginate, but ALL results show on e...

问题:

UPDATE***I am attempting to paginate the result of this foreach loop. This ALMOST works. Im able to get all of the information I need to paginate, but ALL results show on each page. The record count is correct, the generated page numbers are correct. All I'm missing is having the correct number of records display to each page. I understand I need to add the "LIMIT" portion to the sql but where?

UPDATE#2 - LIMIT was working, BUT, I found that the records displayed are treated as just 1 record because they reside in a list in 1 field. So, I need to somehow explode the result into separate pieces for an accurate count. I hope that makes sense.

//$page is generated on another page and is working correctly

   $sql = mysqli_query($con, "SELECT * FROM profile_tbl WHERE X_reg_id = '$var_reg_id'");

    while($field = mysqli_fetch_assoc($sql)){
        $list = $field['profile_choose_them'];
        $list_count = preg_split("/((r?n)|(rn?))/", $list);
        $records_per_page = 3;  
        $item_count= count($list_count);
        $item_count_adj_total_records = ($row_count-1);
        $total_pages = ceil($item_count_adj_total_records/$records_per_page);
        $offset = (($page-1)*$records_per_page);

    }

        foreach(preg_split("/((r?n)|(rn?))/", $list) as $id){    

                   $single = mysqli_query($con, "SELECT * FROM profile_tbl WHERE X_reg_id = '$id'");

                        while($display = mysqli_fetch_assoc($single)){

                            echo '<div><img src="'.$display["profile_pic_main"] .'"></div>';       

                        }

        }

for($page=1;$page<=$total_pages;$page++){
    echo '<a href="../../'.$var_return_ref.'?page='.$page.'">'.$page.'</a> ';
}   

I tried this, but it does not display my items, only page numbers

$single = mysqli_query($con, "SELECT * FROM profile_tbl WHERE X_reg_id = '$id' LIMIT ($offset, $item_count_adj_total_records)");

回答1:

Since you ask about foreach loop specifically, I am guessing that is the part you need to paginate. It seems to loop over set of multiple IDs.

The most brute force way to split such array into pages on pure PHP level would be to chunk it:

$ids_array = preg_split("/((r?n)|(rn?))/", $my_fields['profile_choose_them']);
$pages = array_chunk( $ids_array, 10 );

foreach( $pages[0] as $assign_id ) { // this would loop through first 10 items

}

$pages will contain original array split into arrays of 10 elements. So each entry in $pages could be treated as set of IDs for a single page.

  • 发表于 2019-02-22 05:26
  • 阅读 ( 176 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除