繁体   English   中英

如何在PHP中合并大的arrays?

[英]How to merge large arrays in PHP?

我有 7 个 arrays 对象。 每个 object 包含数据。 我需要将这些 arrays 合并在一起,我这样做:

$arrayTotal = $array1;
$arrayTotal = array_merge($arrayTotal,$array2)
$arrayTotal = array_merge($arrayTotal,$array3)
$arrayTotal = array_merge($arrayTotal,$array4)
...

一切都很好,直到我拥有大约 700 个项目的总数组(每个子数组有 100 个项目)。 Apache 停止响应,我认为是因为 memory 问题,因为 arrays 太多了。我在第 4 次或第 5 次合并时遇到了问题。

合并它们并避免错误的最佳方法是什么?

更新:

[Sat Sep 15 10:17:36 2012] [notice] Apache/2.2.21 (Win32) PHP/5.3.9 configured -- resuming normal operations
[Sat Sep 15 10:17:36 2012] [notice] Server built: Sep 10 2011 11:34:11
[Sat Sep 15 10:17:36 2012] [notice] Parent: Created child process 3908
[Sat Sep 15 10:17:36 2012] [notice] Child 3908: Child process is running
[Sat Sep 15 10:17:36 2012] [notice] Child 3908: Acquired the start mutex.
[Sat Sep 15 10:17:36 2012] [notice] Child 3908: Starting 64 worker threads.
[Sat Sep 15 10:17:36 2012] [notice] Child 3908: Starting thread to listen on port 8080.
[Sat Sep 15 10:17:53 2012] [notice] Parent: child process exited with status 3221225477 -- Restarting.

这是我的 apache 错误日志。 我确实找到了一些将文件复制到我的 system32 文件夹的解决方案,但它们没有用

array_merge可以接受无限数量的 arguments,因此您可以将它们全部放在一个 function 调用中:

$arrayTotal = array_merge($array1,$array2,$array3...);

这应该可以解决问题,因为我过去使用 arrays 处理过数千个项目,没有任何问题。

使用 + 比使用 array_merge 更优化

像这样写,速度更快,资源更少,看来你有问题

$arrayTotal = $array1 + $array2 + $array3 + $array4; //add as much as you need :)

注意:感谢@ficuscr,来自 php array_merge 页面,真正重要的是要注意

如果要将 append 个数组元素从第二个数组转移到第一个数组,同时不覆盖第一个数组中的元素并且不重新索引,请使用 + 数组联合运算符

简而言之,如果您只想 append 东西,而不关心重复项,请使用 +

问题不在 array_merge 中,而是在我对外部文件所做的 curl 中。 正如我所见,文件对于 curl 来说太大了,然后我们遇到了 memory 问题,在 php.ini 中增加 memory 并没有解决问题

就峰值 memory 而言,与array_merge($a, $b)[...$a, ...$b]相比array_push($a, ...$b)使用最少 memory。 峰顶Memory使用对比:

  1. array_push($a, ...$b) => $peakMemory = $aMemory + $bMemory;
  2. $a = array_merge($a, $b) => $peakMemory = 2*$aMemory + $bMemory;
  3. $a = [...$a, ...$b] => $peakMemory = 2*$aMemory + $bMemory;

此外,如果您使用array_merge省略号运算符,以减少峰值 memory 的使用,请确保将返回值分配给最大的数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM