由于内存原因,无法通过从文件中读取 500,000 个条目来填充数组

问题描述 投票:0回答:1

我正在将大约 500.000 个条目解析到一个数组中

$properties
:

$properties = array();
$handle = fopen($file_path, "r");
if ($handle) {
    while (($str = fgets($handle)) !== false) {
        if (strlen($str) && $str[0] == '#') {
            $pdate = substr($str, 1);
            $date = rtrim($pdate);
            $formatted = DateTime::createFromFormat('* M d H:i:s T Y', $date);
        }
        $str = rtrim ($str, "\n");
        $exp = explode ('=', $str);
        if (count($exp) == 2){
            $exp2 = explode('.', $exp[0]);  
            if (count($exp2) == 2) {
                if ($exp2[1] == "dateTime") {
                    $s = str_replace("\\", "", $exp[1]);
                    $d = strtotime($s);
                    $dateTime = date('Y-m-d H:i:s', $d);
                    $properties[$exp2[0]][$exp2[1]] = $dateTime;
                } else {
                    $properties[$exp2[0]][$exp2[1]] = $exp[1];
                }
            } else {
                $properties[$exp[0]] = $exp[1];
            }
        } 
    }
    fclose($handle);
} else {
    echo "error";
}

到目前为止,效果很好,但我需要将数组分割成块,因为否则数组太大而无法使用。

$properties_chunk = array_chunk($properties, 10000, true);

但是现在我遇到了问题,

$properties_chunk
数组没有创建。系统崩溃。这太多了。但现在我能做什么呢?

数组最终应该是这样的:

array(4) {
  [0]=>
  array(10000) {
    ["12345"]=>
    array(5) {
      ["dateTime"]=>
      string(19) "2016-10-12 19:46:25"
      ["fileName"]=>
      string(46) "monkey.jpg"
      ["path"]=>
      string(149) "Volumes/animals/monkey.jpg"
      ["size"]=>
      string(7) "2650752"
    }
    ["678790"]=>
    array(5) {
      ["dateTime"]=>
      string(19) "2016-10-12 14:39:43"
      ["fileName"]=>
      string(45) "elephant.jpg"
      ["path"]=>
      string(171) "Volumes/animals/elephant.jpg"
      ["size"]=>
      string(7) "2306688"
    }

... and so on.
php arrays readfile chunks
1个回答
1
投票

如果使用 array_splice,项目将从输入数组移动到结果数组。

这应该意味着内存使用应该保持不变。

这将与 array_chunk 执行相同的操作,但希望内存消耗更少。

$arr = [1,2,3,4,5,6,7,8,9,10];
$n = 10000;
$count = (count($arr)/$n)-1; // do not splice the last items in loop
For($i=0; $i<$count; $i++){
    $res[] = array_splice($arr, 0,$n);
}
$res[] = array_splice($arr, 0,count($arr)); 
// here we splice the last items from arr to $res. 
// Notice how we splice count($arr) instead of $n. 
// If count($arr) == $n we could have done it in the loop. 
// But if we assume they are not, array_splice in the loop will create empty items. This line will not.

Var_dump($res, $arr); // $res has all values, $arr is empty

https://3v4l.org/XDpdI

© www.soinside.com 2019 - 2024. All rights reserved.