尝试这样的事情:
更新了代码,因此您也可以加载文件,因为您有内存问题。考虑:如果加载数据量已经造成内存问题,那么您的最终结果(数组)也可能会产生内存问题!因为那是更多的数据!
所以这将按行读取,因此它不会直接将整个文件加载到内存中。但是,由于您有内存问题,您可能不应该写入数组,而是写入数据库。否则内存问题将不断出现。
<?PHP
/*
* Example when small amount of data is in a string
*/
/*
//your input
$str='1945/01/05 BA 87 34 1 59 50
1945/01/05 CA 18 17 45 49 82
1945/01/13 BA 6 66 1 16 48
1945/01/13 CA 40 60 32 50 80';
//we work per line
$lines=explode("\n", $str);
//loop each line
foreach($lines AS $line) {
*/
/*
* Example when big amount of data is in a file
*/
//this will contain the end result
$result=array();
$filename='lines.txt'; //contains the data like in your question
$fp = fopen($filename,'r');
while($line=fgets($fp)) {
//explode each line on space so we get the different fields
$fields=explode(' ', $line);
//we remove the date, not needed
unset($fields[0]);
//we get the key (BA/CA/etc) and remove it also
$key=$fields[1];
unset($fields[1]);
//we write the result to the array
//using array_values so the indexes are from 0-4 again
//because we removed items
$result[$key][]=array_values($fields);
}
fclose($fp);
//show the result in html
echo '<pre>';
print_r($result);
问题改变了
这确实回答了评论中提出的问题,而不是实际问题。
<?PHP
/*
* Example when big amount of data is in a file
*/
//this will contain the end result
$result=array();
$filename='lines.txt'; //contains the data like in your question
$fp = fopen($filename,'r');
while($line=fgets($fp)) {
//explode each line on space so we get the different fields
$fields=explode(' ', $line);
//we remove the date, not needed
unset($fields[0]);
//we get the key (BA/CA/etc) and remove it also
$key=$fields[1];
unset($fields[1]);
//We start counting the numbers
foreach($fields AS $nr) {
$nr=trim($nr);
if(empty($result[$key][$nr])) {
$result[$key][$nr]=1;
}else{
$result[$key][$nr]++;
}
}
}
fclose($fp);
//show the result in html
echo '<pre>';
print_r($result);