简体   繁体   中英

Calculate number of pages using PHP Maths and Round

I have a given number of potential posts. We don't know how many there are but the system is set up to show 12 per page. Along the bottom I would like it to display the number of pages.

So first if we get the posts:

<?php $pages =  get_posts('category_name=news'); ?>

Now what we want to do is

  1. work out how many posts it has found
  2. divide that number by 12
  3. round that number up to the nearest whole number (UP never down)
  4. divide that number by 1 and give how many times 1 goes into it.
  5. thus giving as many page numbers as needed.

The ideas is to have them lined up as 1 | 2 | 3 | 4 | 5 etc..

Any ideas?

You're over thinking it. If you know the number of results and the max number of results per page, then you know how many pages you need. I suppose this is WordPress because you've used get_posts, so that should return an array containing the posts, so:

<?php
$max_per_page = 12; //Max results per page

$posts = get_posts('category_name=news');
$total_posts = count($posts);  //Total number of posts returned
$pages = ceil($total_posts / $max_per_page);

for($i = 1;$i <= $pages;$i++) 
{
     echo '<a href="?page=' . $i . '">' . $i . '</a>';  //Or whatever the link needs to be
     if($i != $pages)
     {
         echo "|"
     }
}
?>
  1. work out how many posts it has found

    SELECT COUNT(*) FROM *table* WHERE *conditions*...

  2. divide that number by 12

    SELECT COUNT(*)/12 AS num_pages FROM *table* WHERE *conditions*...

    OR

    $count = mysql_query(*see #1*)/12.0; // NOT JUST 12!

  3. round that number up to the nearest whole number (UP never down)

    $count = ceil($count);

  4. divide that number by 1 and give how many times 1 goes into it.

    REALLY?? DIVIDING ANY NUMBER BY 1 RETURNS ITSELF!

  5. thus giving as many page numbers as needed.

    Not really. How would you know what particular page the user is currently on? How do you plan on actually paginating posts? If the posts are already populated, you are wasting 1-2 queries every time, just for your pagination.

You are basically trying to make pagination, but without knowing a lot of SQL, you're better off using an existing solution (or at least re-factor the existing code to limit queries)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM