编程面试题
1.自定义一个分页函数,传参当前页数、总页数,输出以下
1...34567...10
123456...10
1 //$showPage是掐头去尾的显示数量 2 //这个函数的重点就在于起始值和结束值的运算 3 function page($currentPage,$totalPages,$showPage=5) 4 { 5 $pageStr = ""; 6 $from = max(1,intval($currentPage - $showPage/2)+1); 7 $to = $from==1?$from + $showPage:$from + $showPage-1; 8 if ($to > $totalPages) { 9 $to = $totalPages; 10 $from = max(1, $to - $showPage + 1); 11 } 12 13 $pageStr .= '<div class="page-nav">'; 14 $pageStr .= '<ul>'; 15 16 // 当当前页大于1的时候, 才会显示上一页和首页 17 if($from!=1) { 18 $pageStr .= '<li><a href="?p=1"> 1 </a></li>'; 19 } 20 21 if ($from > 2) { 22 $pageStr .= "<li><a href=?p=".($currentPage - 1)."> ... </a></li>"; 23 } 24 25 for($i=$from; $i<=$to; $i++) { 26 if ($i != $currentPage) { 27 $pageStr .= "<li><a href='?p=".$i."'> {$i} </a></li>"; 28 } else { 29 $pageStr .= "<li><span class='curr-page'> {$i} </span></li>"; 30 } 31 } 32 33 if ($to < $totalPages && $to<($totalPages-1)) { 34 $pageStr .= "<li><a href=?p=".($currentPage+1)."> ... </a></li>"; 35 } 36 37 38 // 当当前页小于总页数的时候, 才会显示下一页和尾页 39 if ($to!=$totalPages) { 40 $pageStr .= "<li><a href='?p=".$totalPages."'>$totalPages</a></li>"; 41 } 42 43 $pageStr .= '</div>'; 44 $pageStr .= '</ul>'; 45 46 return $pageStr; 47 } 48 $p = isset($_GET['p'])?intval($_GET['p']):1; 49 echo page($p, 40);//echo