有问题的代码:
private function pageLinks($num, $page = 1, $search = false, $ne = false) {
$query = ($search) ? '&query='.$search : null;
$by = (is_numeric($ne)) ? '&by='.$ne : null;
$links = 'Page(s):<a href="search.php?page=1' . $query . $by . '" class="tableLink">1</a>';
$count = 1;
$npp = $this->numPerPage;
$buttons = 9;
$half = 4;
for($i = 1; $i <= $num; $i++) {
if(($i%$npp) === 0) {
$count++;
}
}
if($count < $buttons) {
for($i = 2; $i <= $count; $i++) {
$links .= '<a href="search.php?page=' . $i . $query . $by . '" class="tableLink">' . $i . '</a>';
}
} elseif($page <= ($half + 2)) {
for($i = 2; $i <= $buttons; $i++) {
$links .= '<a href="search.php?page=' . $i . $query . $by . '" class="tableLink">' . $i . '</a>';
}
$links .= '...<a href="search.php?page=' . $count . $query . $by . '" class="tableLink">' . $count . '</a>';
} elseif($page <= ($count - ($half + 2))) {
$links .= '...';
for($i = $half; $i > 0; $i--) {
$links .= '<a href="search.php?page=' . ($page - $i) . $query . $by . '" class="tableLink">' . ($page - $i) . '</a>';
}
$links .= '<a href="search.php?page=' . ($page - $i) . $query . $by . '" class="tableLink">' . ($page - $i) . '</a>';
for($i = 1; $i <= $half; $i++) {
$links .= '<a href="search.php?page=' . ($page + $i) . $query . $by . '" class="tableLink">' . ($page + $i) . '</a>';
}
$links .= '...<a href="search.php?page=' . $count . $query . $by . '" class="tableLink">' . $count . '</a>';
} else {
$links .= '...';
for($i = $buttons - 1; $i >= 0; $i--) {
$links .= '<a href="search.php?page=' . ($count - $i) . $query . $by . '" class="tableLink">' . ($count - $i) . '</a>';
}
}
return($links);
}
这样调用方法:
$links = $this->pageLinks($count, $page, $url, $ne);
变量就是这样:
$count
=数据库(int)
中的客户总数
$page
=从(int)
生成的当前页面
$url
=搜索(String)
的名称或电子邮件
$ne
=用于搜索字符串,按名称(1)或电子邮件(2)(int)
输出就像(作为链接):
Page:1
2
3
4
5
6
7
8
{{ 1}} ... 9
或者如果你在中间(第20页):
Page(s):33
... 1
16
17
18
19
20
{{1} } 21
22
... 23
现在并不总是通过搜索功能调用,因此24
和33
的默认值,但这不是很重要。我的问题是有一种更清洁的方法来处理这些链接的构建吗?还是我坚持使用这个循环群?
答案 0 :(得分:1)
在codereview.stackexchange.com的人们的帮助下,我找到了我需要的东西。你可以find the answer here for a more in-depth approach,但如果有人遇到这个并且很好奇,这里是更新后的代码:
private function pageLinks($num, $page = 1, $search = false, $ne = false) {
$query = ($search && is_numeric($ne)) ? "&query=" . $search . "&by=" . $ne : null;
$links = "Page(s):" . $this->page_link(1, $query);
$npp = $this->numPerPage;
$half = 4;
$count = floor($num / $npp) + 1;
$from = $page - $half;
if($from <= 2) {
$from = 2;
}
$to = $page + $half;
if($to >= $count - 1) {
$to = $count - 1;
}
if($from > 2) {
$links .= "...";
}
for($i = $from; $i <= $to; $i++) {
$links .= $this->page_link($i, $query);
}
if($i < $count) {
$links .= "...";
}
$links .= $this->page_link($count, $query);
return($links);
}
private function page_link($num, $query) {
return("<a href=\"search.php?page=" . $num . $query . "\" class=\"table_link\">" . $num . "</a>");
}