使用 PHP Maths 和 Round 计算页数
我有一定数量的潜在职位。我们不知道有多少个,但系统设置为每页显示 12 个。我希望它在底部显示页数。
首先,如果我们得到帖子:
<?php $pages = get_posts('category_name=news'); ?>
现在我们要做的是
- 计算出它找到了多少帖子,
- 将该数字除以 12
- ,将该数字向上舍入到最接近的整数(向上,永不向下)
- 将该数字除以 1,并给出如何计算很多次1进入其中。
- 从而根据需要给出尽可能多的页码。
我们的想法是将它们排列为 1 | 2 | 3 | 4 | 5等..
有什么想法吗?
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
- work out how many posts it has found
- divide that number by 12
- round that number up to the nearest whole number (UP never down)
- divide that number by 1 and give how many times 1 goes into it.
- 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你想多了。如果您知道结果数和每页的最大结果数,那么您就知道需要多少页。我想这是 WordPress,因为您使用了 get_posts,因此应该返回一个包含帖子的数组,因此:
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:
计算出它找到了多少帖子
SELECT COUNT(*) FROM *table* WHERE *conditions*...
将该数字除以 12
SELECT COUNT(*)/12 AS num_pages FROM *table* WHERE *conditions*...
或者
$count = mysql_query(*参见 #1*)/12.0; // 不仅仅是 12!
将该数字向上舍入到最接近的整数(向上,永不向下)
$count = ceil($count);
将该数字除以 1,并给出 1 出现的次数。
真的吗?任何数字除以 1 都会返回
从而根据需要提供尽可能多的页码。
不是真的。您如何知道用户当前位于哪个特定页面?您打算如何对帖子进行实际分页?如果帖子已经填充,那么您每次都会浪费 1-2 个查询,只是为了分页。
您基本上是在尝试进行分页,但在不了解大量 SQL 的情况下,最好使用现有的解决方案(或者至少重构现有代码以限制查询)
work out how many posts it has found
SELECT COUNT(*) FROM *table* WHERE *conditions*...
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!
round that number up to the nearest whole number (UP never down)
$count = ceil($count);
divide that number by 1 and give how many times 1 goes into it.
REALLY?? DIVIDING ANY NUMBER BY 1 RETURNS ITSELF!
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)