Php 在.txt文件中读取和写入大型数组

Php 在.txt文件中读取和写入大型数组,php,arrays,Php,Arrays,我正在尝试执行下面的代码,当我在终端中加载文件时,我不断收到一条消息,导致读取失败。我知道我正在使用大量内存,所以我将内存限制设置为apache上允许的最大内存量。我有一个名为codes.txt的文本文件,其中包含从0到1000000的数字列表。我需要随机化这些数字的出现,然后将它们的新顺序写入一个新的文本文件。然后,我需要将它们的新出现存储在一个数组中 ini_set('memory_limit', '2048M'); // Get all of the values from the .t

我正在尝试执行下面的代码,当我在终端中加载文件时,我不断收到一条消息,导致读取失败。我知道我正在使用大量内存,所以我将内存限制设置为apache上允许的最大内存量。我有一个名为codes.txt的文本文件,其中包含从0到1000000的数字列表。我需要随机化这些数字的出现,然后将它们的新顺序写入一个新的文本文件。然后,我需要将它们的新出现存储在一个数组中

ini_set('memory_limit', '2048M');

// Get all of the values from the .txt file 
// and store them in an array
$file = fopen("codes.txt", "r");
$codes = array();

while(!feof($file)) {
    $codes[] = trim(fgets($file));
}

fclose($file);

// Randomize the elements in the array
shuffle($codes);

// Write each element in the shuffled array to a new .txt file
$new_file = fopen("new_codes.txt", "w");

for($i=0;$i<1000000;$i++) {
      fwrite($new_file, $codes[$i].PHP_EOL);
}

fclose($new_file);

// Put all of the new elements into a new array
$new_file = fopen("new_codes.txt", "r");
$code = array();

while(!feof($new_file)) {
    $code[] = trim(fgets($new_file));
}

print_r($code);

不用担心新的数组,$代码已经有了它们。如果需要关闭,请重新打开文件并将其读入新数组,内存是问题所在,然后在打开文件之前先使用unset$代码杀死旧数组

ini_set('memory_limit', '2048M');

// Get all of the values from the .txt file
// and store them in an array
$file = fopen("codes.txt", "r");
$codes = array();

while (!feof($file)) {
    $codes[] = trim(fgets($file));
}

fclose($file);

// Randomize the elements in the array
shuffle($codes);

// Write each element in the shuffled array to a new .txt file
$new_file = fopen("new_codes.txt", "w");
foreach($codes as $k => $v){
    fwrite($new_file, $v.PHP_EOL);
}

fclose($new_file);

你可以删掉很多代码$codes=文件'codes.txt';洗牌$代码;文件\u put\u contentsimpledephp\u EOL,$code;另外,写出你的文件,删除$codes数组,然后读回刚才生成的完全相同的文件有什么意义?你已经有了数组中的数字作为开始。关系数据库可以在Flash中解决这个问题。另外,为什么要逐行将无序数组写入文件?也许使用内爆将它连接到回车上并写出它?每次加载此文件时,我都需要一个随机顺序的代码数组的静态列表。下一次由同一用户加载文件时,需要再次使用该顺序