对许多结果有效而优雅的分页

时间:2014-02-24 16:58:32

标签: php pagination

我写了这个函数来生成大量页面和有效导航的页面链接。 我想优化此代码以获得更好的圆值,具体取决于到当前页面的距离。 我用$ r和$ c来调整结果。 $ c是调整中心点以获得舍入值。 例如,当current_page = 1或1000时,我得到了一个完美的结果:

[1] 2 3 .. 10 .. 20 .. 50 .. 100 .. 500 .. 1000 .. 1789 next
previous 1 .. 500 .. 900 .. 950 .. 980 .. 990 .. 998 999 [1000] 1001 1002 .. 1010 .. 1020 .. 1050 .. 1100 .. 1500 .. 1789 next

但是current_page = 1350并不完美:

previous 1 .. 400 .. 900 .. 1300 .. 1330 .. 1340 .. 1348 1349 [1350] 1351 1352 .. 1360 .. 1370 .. 1400 .. 1450 .. 1500 .. 1789 next

当前页面在两个方向上的前3个步骤值都可以,但值900和400很奇怪。 500和1000会更好。 我必须更好地调整范围$ r和动态中心点$ c,但我找不到优雅的解决方案。

请帮忙。

<?
function pagination_test(){
  $page_var = "current_page";
  $cur_page = isset($_GET[$page_var]) ? $_GET[$page_var] : 1;
  $page_count = 1789; // count of pages for test
  $steps = Array(10,20,50,100,500,1000,2000,5000,10000); // steps around current page for effective navigation in many results
  $link_count = 3; // link count direct around current page
  $stepspace = ".. ";

  $pagelinks = ""; $space = $stepspace; // set output & spacer    
  if($page_count > 1 && $cur_page > 1)
    $pagelinks .= "<a href='?{$page_var}=".($cur_page-1)."'>previous</a> "; // previous page
  for($f=1; $f<=$page_count; $f++){

    // here is my problem
    $r = pow(10,strlen((string)abs($f-$cur_page)+1)-1); // get range - distance to cur-page? (10,100,1000,10000)
    $c = round($cur_page/$r)*$r; // get center point for dynamic step - snap to range

    if($cur_page==$f) $pagelinks .= "<a class=current>[{$f}]</a> "; // current page
    else if( $f == 1 || $f == $page_count || $link_count > abs($f-$cur_page) || in_array(abs($f-$c), $steps)){
      $pagelinks .= "<a href='?{$page_var}={$f}'>{$f}</a> "; // stepped & selected
      $space = $stepspace." "; //set spacer for next step
    }else{
      $pagelinks .= $space;
      $space = ""; // only one spacer behind steps
    }   
  }
  if($page_count > 1 && $cur_page < $page_count)
    $pagelinks .= "<a href='?{$page_var}=".($cur_page+1)."'>next</a>"; // next page
  return trim($pagelinks);  

}
echo pagination_test();
?>

0 个答案:

没有答案