S
S
Strange2011-09-09 10:43:34
Algorithms
Strange, 2011-09-09 10:43:34

pagination algorithm?

We need an algorithm like this pagination:
33dd1cf5.png
An implementation option, but it is not very beautiful:

$count_entrys = 148; // количество записей
$entry_on_page = 15; // количество записей на странице
$current_page = 5; // текущая страница
$max_pages_list = 5; // сколько номеров страниц показывать

$count_pages = ceil($count_entrys / $entry_on_page);

$first_page = $current_page - (int) ($max_pages_list / 2);
if ( $first_page <= 1 )
  $first_page = 1;
else {
  if ( $count_pages - $first_page < $max_pages_list ){
    $first_page = $count_pages - $max_pages_list + 1;
    if ( $first_page <= 1 )
      $first_page = 1;
  }
}
$last_page = $first_page + $max_pages_list - 1;
if ( $last_page > $count_pages )
  $last_page = $count_pages;

if ( $first_page != 1 )
  echo '< |';

for ( $i = $first_page; $i <= $last_page; $i++ ){
  echo ' ', $i, ' |';
}

if ( $last_page < $count_pages )
  echo ' >';

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Anatoly, 2011-09-09
@Strange

And what exactly do you find unattractive? Working option? Does it work without errors? You probably no longer have a job other than to “make beautiful” from the standard pagination algorithm. If you really really want to make it “beautiful”, you can replace one of the ifs (which calculates pages) with php.net/manual/en/function.range.php , and the for with implode + array_map. There will be less code, but believe me, what you have now is standard code, almost everyone writes this way, and it will be easier for you and others to change it in the future.

S
Strange, 2011-09-09
@Strange

The version is working and was written by me after discovering a small bug in the previous one.
He asked in order to put an end to the question for himself and not look for a better option. If you get a standard code - good.
Thanks for the answer.

S
Seldon, 2011-09-09
@Seldon

$count_entries = 148; // number of entries
$entry_on_page = 15; // number of entries per page
$current_page = 5; // current page
$max_pages_list = 5; // how many page numbers to show
$count_pages = ceil($count_entrys / $entry_on_page);
$from = $current_page + ceil(($max_pages_list-1) / 2);
$to = $current_page + floor(($max_pages_list-1) / 2);
echo "some link for previos page $current_page-1";
for($i = $from; $i <= $to; $i++ ) {
echo "somelink for page number $i";
}
echo "some link for next page $current_page+1";
Accordingly, add checks for the existence of the previous and next pages here, I think it's understandable.
In general, a strange question for Habr, there is nothing to do with the algorithm, then in fact there is nothing, everything is elementary and simple. And besides, you didn’t even describe how it should work and the arrows on the sides lead where.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question