我想在PHP中创建一个大小为2000x2000(400万条目)的二维数组。但是似乎我在这里用完了内存,但错误出现的方式使我感到困惑。
当我定义该数组并使用array_fill命令最初填充它,并将数组(矩阵)中的每个位置初始化为0时,没有问题。
然而,如果我尝试迭代数组并填充每个位置为0,则会用完内存。
我认为一旦我运行array_fill,它就在那一点上分配了内存,循环过程中不应该用完内存。
当然,这只是代码的简化版本。在我的实际应用程序中,我将使用X和Y坐标从另一个表查找值,处理它,然后将其存储在我的矩阵中。这些将是浮点值。
请问有人可以帮忙解释一下吗?我应该用其他方法吗?
谢谢!
<?php
// Set error reporting.
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
// Define Matrix dimensions.
define("MATRIX_WIDTH", 2000+1);
define("MATRIX_HEIGHT", 2000+1);
// Setup array for matrix and initialize it.
$matrix = array_fill(0,MATRIX_HEIGHT,array_fill(0,MATRIX_WIDTH,0));
// Populate each matrix point with calculated value.
for($y_cood=0;$y_cood<MATRIX_HEIGHT;$y_cood++) {
// Debugging statement to see where the script stops running.
if( ($y_cood % 100) == 0 ) {print("Y=$y_cood<br>"); flush();}
for($x_cood=0;$x_cood<MATRIX_WIDTH;$x_cood++) {
$fill_value = 0;
$matrix[$y_cood][$x_cood]=$fill_value;
}
}
print("Matrix width: ".count($matrix)."<br>");
print("Matrix height: ".count($matrix[0])."<br>");
?>
memory_limit = 128M; 脚本可消耗的最大内存量(128MB)
。我个人不建议相信不稳定脚本行为所导致的结果。 - Mark Zucchini