php 处理大数组,如何在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

$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

$output = implode("\n", $array_sliced);

}

echo "

"; print_r($output); echo "
";

这段代码的作用是,它生成以下数据(从(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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值