English 中文(简体)
巨大数组上负偏移的array_slice
原标题:array_slice with negative offset on huge arrays
  • 时间:2011-05-27 14:01:23
  •  标签:
  • php
  • arrays

由于我不在这里讨论的原因,我被迫解析一个大目录的文件(我们说的是100.000<;x<;1.000.000+),并将文件列表作为数组返回。

我已经在缓存文件列表,问题是阵列切片

是的,因为有一个catch,所以这个文件列表必须“分页”,以块16的形式返回它们。

我正在做的是:

$items_per_page = 16;
$offset = ($current_page * $items_per_page) + $items_per_page;
array_slice($array,-$offset,$items_per_page);

It s easy to see that in a few pages we ll have huge offsets. Also starting from page four (offset = -80) there is a huge performance hit.

我可以用什么来代替array_slice来实现这种数组分页?

谢谢

最佳回答

如果数组是数字索引的(不跳过数字),可以尝试使用for循环。

$items_per_page = 16;
$offset = ($current_page * $items_per_page) + $items_per_page;
$chunk = array();
for($i=$offset;$i<$offset+$items_per_page;$i++){
    $chunk[] = $files[$i];
}

编辑:

我只是做了一些基准测试来获得一个想法。在我们的服务器上,有一个由100万个项目组成的数组,每个项目处理100次,array_slice()的处理时间为2.5689ms。使用for循环耗时0.0031ms。

问题回答

考虑创建、填充和操作DB表,而不是在内存中执行所有这些操作。它上的索引将允许您以合理的性能对文件进行分页。





相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签