如何在PHP中处理非常大的数组?

我有这段代码.

$input = 4;
$list_N = array('0', '1');
for($n=1; $n<=$input; $n++) {

    if($n%2 == 0) {
        $c++;
    }

    $reverse_list_N = array_reverse($list_N);

    $A = array();
    $B = array();

    for($i=0; $i<count($list_N); $i++) {
        $A[] = '0' . $list_N[$i];
        $B[] = '1' . $reverse_list_N[$i];
    }

    $list_N = array_merge($A[], $B[]);

    if($n == 1) {
        $list_N = array('0', '1');
    }
}
$array_sliced = array_slice($list_N, -1*$input, $input);
for($i=0; $i<count($array_sliced); $i++) {
    $output = implode("\n", $array_sliced);
}
echo "<pre>"; print_r($output); echo "</pre>";

这段代码的作用是,它生成以下数据(从(0,1)开始):

0,1
00, 01, 11, 10
000, 001, 011, 010, 110, 111, 101, 100
....... and so on

当$input = 4时;输出是:

1010
1011
1001
1000

正如您所看到的,在每个循环之后,$list_N数组中的元素比前一个元素要多一倍.如果$input = 25,那么这个步伐;然后数组将有33554432个非常巨大的元素.这就是我找不到解决方案的问题.当$input = 60时,我收到此错误

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 36 bytes)

在这条线上

$list_N = array_merge($A, $B);

即使将内存限制设置为2G也无法解决问题.那么,我如何优化我的代码以使内存相同.或者,还有其他解决方案吗?

更新:以下步骤用于生成数据.

$list_N is an array
$reverse_list is the reverse of $list_N
0 is appended in the beginning of every element in the $list_N array and stored in $A
1 is appended in the beginning of every element in the $reverse_list_N array and stored in $B
Array $A and array $B are merged and is stored in $list_N.
The main loop runs for $input number of times and the last $input number of elements are displayed from the final array.

最佳答案 解:

尝试使用SplFixedArray!

关于:

一个SplFixedArrayis

about 37% of a regular “array” of the same size

The SplFixedArray class provides the main functionalities of array. The advantage is that it allows a faster array implementation.

来自:Documentation Page

例:

$startMemory = memory_get_usage();
$array = new SplFixedArray(100000);
for ($i = 0; $i < 100000; ++$i) {
    $array[$i] = $i;
}
echo memory_get_usage() - $startMemory, ' bytes';

进一步阅读:

阅读更多:http://nikic.github.io/2011/12/12/How-big-are-PHP-arrays-really-Hint-BIG.html

梅西耶解决方案:

另一个可以帮助的解决方案,我不建议覆盖默认的内存容量.你可以这样做:

ini_set('memory_limit', '-1')

进一步阅读:

http://php.net/memory_limit

点赞