PHP 中的数组大小限制

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5925885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:54:50  来源:igfitidea点击:

Array size limit in PHP

phparrays

提问by Michael

I am wondering is there a size limit for array in php 5? I wrote a php script to change the last element of each line in a file. print out the content of a modified file, when I run the script on a small-sized file (i.e. each line comprises 4 values), it will work. When I run it on a larger file (like 60000 lines, each of which comprises 90 values), it does not change a bit of the original file, but the script did not throw any exception message during runtime. What is this problem?

我想知道 php 5 中的数组是否有大小限制?我编写了一个 php 脚本来更改文件中每一行的最后一个元素。打印出修改后的文件的内容,当我在一个小文件(即每行包含 4 个值)上运行脚本时,它会起作用。当我在一个更大的文件(比如 60000 行,每行包含 90 个值)上运行它时,它不会改变原始文件的一点点,但脚本在运行时没有抛出任何异常消息。这是什么问题?

回答by ashurexm

You could be running out of memory, as your array size is (in theory) only limited by the amount of memory allocated to the script. Put ini_set('memory_limit', '1024M');in the beginning of your script to set the memory limit to 1 GB. You may need to increase this even higher for best results.

您可能会耗尽内存,因为您的数组大小(理论上)仅受分配给脚本的内存量的限制。放在ini_set('memory_limit', '1024M');脚本的开头,将内存限制设置为 1 GB。为了获得最佳效果,您可能需要将其提高得更高。

回答by Eelke

As manyxcxi says you will probably have to increase the memory_limit. Sometimes you can also reduce memory usage by unsetting large variables with unset($var). This is only needed when the variable stays in scope far past it's last point of use.

正如 manyxcxi 所说,您可能必须增加 memory_limit。有时您还可以通过使用 unset($var) 取消设置大变量来减少内存使用。仅当变量停留在其最后使用点之后的范围内时才需要这样做。

Are you by any chance now reading the whole file, tranforming it and then writing the new file? If so you can reduce memory usage by working in a loop where you read a small part, process it and write it out and repeat that until you reach the end of the file. But only if the transformation algorithm doesn't need the whole file to transform a small part.

您现在是否有机会读取整个文件,对其进行转换然后写入新文件?如果是这样,您可以通过在循环中读取一小部分,处理它并将其写出并重复该操作,直到到达文件末尾来减少内存使用量。但前提是转换算法不需要整个文件来转换一小部分。