简体   繁体   English

使用PHP Maths和Round计算页数

[英]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. 我们不知道有多少,但系统设置为每页显示12个。 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 将该数字除以12
  3. round that number up to the nearest whole number (UP never down) 将该数字舍入到最接近的整数(UP永不下降)
  4. divide that number by 1 and give how many times 1 goes into it. 将该数字除以1并给出1进入它的次数。
  5. thus giving as many page numbers as needed. 从而根据需要提供尽可能多的页码。

The ideas is to have them lined up as 1 | 想法是将它们排成1 | 2 | 2 | 3 | 3 | 4 | 4 | 5 etc.. 5等..

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: 我想这是WordPress,因为你使用了get_posts,所以应该返回一个包含帖子的数组,所以:

<?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 将该数字除以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) 将该数字舍入到最接近的整数(UP永不下降)

    $count = ceil($count);

  4. divide that number by 1 and give how many times 1 goes into it. 将该数字除以1并给出1进入它的次数。

    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. 如果帖子已经填充,那么每次都会浪费1-2次查询,只是为了您的分页。

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) 您基本上是在尝试进行分页,但是在不了解大量SQL的情况下,最好使用现有的解决方案(或者至少重新考虑现有代码以限制查询)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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