php - 如何优化大型 CSV 文件数据提取的循环
问题描述
我有一个关于代码优化的问题。十多年来,除了简单的循环之外,我没有编写任何代码。
我创建了下面的代码,它工作得很好,但对我的需要来说超级慢。
本质上,我有 2 个 CSV 文件:
- 一个包含大约 500 000 条记录的源 CSV 文件,例如:att1、att2、source_id、att3、att4(实际上大约有 40 列)
- 一个包含大约 1.2 亿条记录的主 CSV 文件,比如说:att1、att2、att3、main_id、att4(实际上大约有 120 列)
对于源文件中的每个 source_id,我的代码都会在主文件中解析 main_id == source_id 的所有行,并将这些行中的每一行写入一个新文件中。
你对我如何优化代码有什么建议吗?
<?php
$mf = "main.csv";
$mf_max_line_length = "512";
$mf_id = "main_id";
$sf = "source.csv";
$sf_max_line_length = "884167";
$sf_id = "source_id";
if (($mf_handle = fopen($mf, "r")) !== FALSE)
{
// Read the first line of the main CSV file
// and look for the position of main_id
$mf_data = fgetcsv($mf_handle, $mf_max_line_length, ",");
$mf_id_pos = array_search ($mf_id, $mf_data);
// Create a new main CSV file
if (($nmf_handle = fopen("new_main.csv", "x")) !== FALSE)
{
fputcsv($nmf_handle,$mf_data);
} else {
echo "Cannot create file: new_main.csv" . $sf;
break;
}
}
// Open the source CSV file
if (($sf_handle = fopen($sf, "r")) !== FALSE)
{
// Read the first line of the source CSV file
// and look for the position of source_id
$sf_data = fgetcsv($sf_handle, $sf_max_line_length, ",");
$sf_id_pos = array_search ($sf_id, $sf_data);
// Go trhough the whole source CSV file
while (($sf_data = fgetcsv($sf_handle, $sf_max_line_length, ",")) !== FALSE)
{
// Open the main CSV file
if (($mf_handle = fopen($mf, "r")) !== FALSE)
{
// Go trhough the whole main CSV file
while (($mf_data = fgetcsv($mf_handle, $mf_max_line_length, ",")) !== FALSE)
{
// If the source_id matches the main_id
// then we write it into the new_main CSV file
if ($mf_data[$mf_id_pos] == $sf_data[$sf_id_pos])
{
fputcsv($nmf_handle,$mf_data);
}
}
fclose($mf_handle);
}
}
fclose($sf_handle);
fclose($nmf_handle);
}
?>
解决方案
推荐阅读
- java - 如何使用 servlet 过滤器拦截对其他应用程序的请求?
- reactjs - 未捕获的 TypeError: (0 , _reactTable.useTable) 不是函数
- javascript - 返回数组中的对象属性
- ruby-on-rails - How to fix ActionController::UnknownFormat error for json rendered reponse in RSpec
- azure-data-factory - 如何在 REST 数据集到 SQL 数据集的映射中使用动态日期
- parse-platform - 如何限制对客户端可见的解析配置参数?
- pentaho - 如何映射来自 2 个输入的字段以生成 1 个输出
- python - 无法设置 QTableView 的行高
- python - 在 Django 中设计正确的模式关系
- python-3.x - 使用python在ms word中的合并单元格上插入数据