需要有关基本循环分页功能的帮助

时间:2018-10-05 07:15:19

标签: php

我需要运行循环功能来显示分页的帮助(我使用jQuery ajax php显示一些数据)。

例如:

<?php
$start_row = 0;
$total_row = 10;

echo "<button>Prev</button>";

for ($i = ($start_row + 1); $i <= $total_row; $i++) {
    if ($i == $current_page) {
        echo "<a style='font-weight: bold;'>[$i]</a>";
    } else {
        echo "<a style='font-weight: normal;'>[$i]</a>";
    }
}

echo "<button>Next</button>";
?>

上面函数的结果将为:

[Prev][1][2][3][4][5][6][7][8][9][10][Next]

但是我想每5页拆分该数字以显示如下:

[Prev][1][2][3][4][5][Next]

但是[6][7][8][9][10]保持隐藏状态

当我单击下一步按钮时,第2页将显示为:

[Prev][2][3][4][5][6][Next]

第5页显示如下:

[Prev][5][6][7][8][9][Next]

直到第10页的末尾将显示为:

[Prev][6][7][8][9][10][Next]

1 个答案:

答案 0 :(得分:0)

As mentioned in a comment, you want to somehow know what page you are on. I assume that this is known in the URI. e.g that your url looks something like:
http://www.example.com/intereesting/articles.php?page=x 

评论说当前页面在start_row post变量中。

What you want to do is irritate from the current page or 1 if not set. 

    $current_page = (isset($_POST['start_row'])) ? $_POST['start_row'] : 1;
    $start_row = $current_page;
    $total_row = $current_page + 5;

    echo "<button>Prev</button>";

    for ($i = $start_row; $i <= $total_row; $i++) {
         if ($i === $current_page) {
             echo "<a style='font-weight: bold;'>[$i]</a>";
          } else {
             echo "<a style='font-weight: normal;'>[$i]</a>";
          }
    }

另一个选择是这样做

$current_page = (isset($_POST['start_row'])) ? $_POST['start_row'] : 1;
echo "<button>Prev</button>";
$i = $current_page;
while ($i  <= $current_page + 5) {
    if ($i === $current_page) {
         echo "<a style='font-weight: bold;'>[$i]</a>"; // This will always be the first value though.
      } else {
         echo "<a style='font-weight: normal;'>[$i]</a>";
      }
    $i++
}