Skip to content

Instantly share code, notes, and snippets.

@lnaia
Last active September 16, 2015 08:35
Show Gist options
  • Save lnaia/9a96b5c8bc95201834ba to your computer and use it in GitHub Desktop.
Save lnaia/9a96b5c8bc95201834ba to your computer and use it in GitHub Desktop.
JR - php
<?php
function getPaginator($current_page, $total_pages, $boundaries, $around) {
$paginator = array();
$suspensionPoints = false;
$paginator[$total_pages] = null;
$paginator[$current_page] = null;
for ( $i=1; $i<=$boundaries; $i++ ) {
$paginator[$i] = null;
$paginator[$total_pages - $i + 1] = null;
}
for ( $i=1; $i<=$around; $i++ ) {
$paginator[$current_page - $i] = null;
$paginator[$current_page + $i] = null;
}
foreach ($paginator as $key => $value) {
if($key < 1 || $key > $total_pages) {
unset($paginator[$key]);
}
}
ksort($paginator);
$paginator = array_keys($paginator);
$paginator_clone = $paginator;
$old_value = false;
$shifts_needed = 0;
//print_r($paginator);
foreach($paginator_clone as $index => $val) {
if ($old_value === false) {
$old_value = $val;
continue;
}
if (($val - $old_value) > 1) {
//echo "gap found at: $index \n";
$position = $index + $shifts_needed;
$first_part = array_slice($paginator, 0, $position, true);
$last_part = array_slice($paginator, $index, count($paginator) - 1, true);
$paginator = array_merge($first_part, ['...'], $last_part);
$shifts_needed += 1;
}
$old_value = $val;
}
echo implode(' ', $paginator) . "\n";
}
getPaginator(6,30,2,2); # [1,2,"...",4,5,6,7,8,29,30]
getPaginator(1,10,2,2); # [1,2,3,9,10]
getPaginator(10,10,10,0); # [1,2,3,4,5,6,7,8,9,10]
getPaginator(5,3,10,10);
getPaginator(4, 5, 1, 0); # [1, "...", 4, 5]
getPaginator(4, 10, 2, 2); # [1, 2, 3, 4, 5, 6, "...", 9, 10]
getPaginator(6, 30, 2, 2); #[1, 2, "...", 4, 5, 6, 7, 8, "...", 29, 30]
getPaginator(1, 10, 2, 2); # [1, 2, 3, "...", 9, 10]
getPaginator(6, 30, 2, 2); # [1, 2, 3, "...", 9, 10]
getPaginator(10, 10, 10, 10); # [1, "...", 4, 5]
/*
got:
1 2 ... 4 5 6 7 8 ... 8 29 30
1 2 3 ... 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3
1 ... 4 5
1 2 3 4 5 6 ... 9 10
1 2 ... 4 5 6 7 8 ... 8 29 30
1 2 3 ... 9 10
1 2 ... 4 5 6 7 8 ... 8 29 30
1 2 3 4 5 6 7 8 9 10
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment