Php 如何将一个巨大的数组分割成块?
我正在将大约50万个条目解析到一个数组Php 如何将一个巨大的数组分割成块?,php,arrays,chunks,Php,Arrays,Chunks,我正在将大约50万个条目解析到一个数组$properties: $properties = array(); $handle = fopen($file_path, "r"); if ($handle) { while (($str = fgets($handle)) !== false) { if (strlen($str) && $str[0] == '#') {
$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\u 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.
如果使用数组拼接,则项目将从输入数组移动到结果数组 这意味着内存使用应该保持不变 这将与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
$arr=[1,2,3,4,5,6,7,8,9,10];
$n=10000;
$count=(count($arr)/$n)-1;//不要拼接循环中的最后一项
对于($i=0;$imaybe而不是数组块,只需在0-10000之间执行For循环。可能不会崩溃?在从文件中读取10000个块时,可以只处理每个块吗?保持计数,处理批处理,然后在继续之前清空它。或者您需要将它们同时放在内存中(排序等)?@iainn我需要立即使用区块与其他阵列进行比较。增加内存限制/超时时间不太可能。让我做一个演示,稍等。看看它的作用:查看项目中的项目总数如何保持不变。Array\u区块将复制输入阵列。注释不用于扩展讨论;此对话这是一个很好的例子。