如何有效地对 PHP 数组进行分页?
我当前有一个使用 URL 参数分页的数组(例如 ....php?page=2&blah=blop&glob=gloo)。
目前,每次加载页面时,都会从查询引擎下载一个 XML 文件,进行解析,然后拉出我想要使用的对象数组。
如何设置才能不必重新加载页面而只需从 XML 文件中读取一次?
我对 PHP 还很陌生,所以请耐心等待。经过一番研究后,我认为 Ajax 适合这个吗?如果我错了,请纠正我。我试图找出一些关于使用 Ajax 进行分页的内容,但我发现最有用的内容是对 mysql 数据库中的数据进行分页,而不是对对象数组进行分页。
任何人都可以提供任何指示吗?我渴望学习。
I have an array currently paginated by using URL parameters (eg. ....php?page=2&blah=blop&glob=gloo).
At the moment, every single time the page loads, an XML file is being downloaded from a query engine, parsed and then im pulling an array of objects out I want to use.
How do I set this up so that I don't have to reload the page and only have to read from the XML file once?
I am fairly new to PHP so please bear with me. After a bit of researching I did I think Ajax is appropriate for this? Please correct me if I am wrong. I tried to find out some stuff on paginating with Ajax but the most useful things I found were for paginating data from a mysql database, not for an array of objects.
Can anyone provide any pointers? I'm eager to learn.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当我需要这个时,我创建一个缓存函数,A) 从原始源加载 XML,然后将其保存到缓存文件夹,或者 B) 从缓存文件夹加载它(如果存在),以及其他标准(例如新鲜度)已满足。
在一个必须从相当慢的服务器检索数据的网站上,我将 A) 放入 cron 作业中,并始终从网站的缓存中读取。
如果您需要大数据分页,这里有一个很好的例子: http://net.tutsplus.com/tutorials/php/how-to-paginate-data-with-php/
When I need this, I create a caching function that either A) Loads the XML from the original source and then saves it to a cache folder, or B) Loads it from the cache folder if it exists, and other criteria (like freshness) is met.
On one site that had to retrieve data from a fairly slow server, I put A) into a cron job and always read from the cache for the website.
If you need large data pagination, here's a good example: http://net.tutsplus.com/tutorials/php/how-to-paginate-data-with-php/
您可以调整您发现的用于处理数据库的 AJAX 来处理您的数据对象,以便页面仅加载一次。
You could adapt the AJAX that you found for working with the database to work with your data object instead, so that the page is only loaded once.
您可以使用
memcached
将 XML 缓存在内存中,也可以将其保存到本地文件并从那里读取。此外,您可以将其保存为一种不同的、更快的格式(可能是
json
?)并将其拆分为文件 - 每个页面一个文件 - 并且仅读取您需要的页面的文件。如果文件是特定于用户的,则其他选项是将其保存在会话中(如果它的数组形式不是太大),或者如果您想将其保存在文件中,则将会话 ID 添加到文件名中。
这完全取决于您想要对文件及其内容执行的操作。
You can cache the XML either in memory using
memcached
or by saving it to a local file and read from there.Additionally you can save it to a different, faster format(maybe
json
?) and split it into files - one file for each page - and only read the file for the page you need.If the file is user-specific then other option would be to save it in the session(if it's not too big in array form), or if you want to save it in a file then prepend the session-id to the file name.
It is all very depending on what you want to do with the file and it's contents.
您可能对 php 分页 类感兴趣。
You may be interested on this class for php paginations.