读取两个 csv 文件,并使用 php 将它们的两列连接成新文件


Read two csv files and concatenate their two columns into new file with php

我想连接两个CSV文件:

网址.csv :

www.text.com/test.html

www.text.com/test1.html

www.text.com/test2.html

颜色.csv :

粉红色

结果应如下所示:

www.text.com/test.html?color=Red

www.text.com/test1.html?color=Red

www.text.com/test2.html?color=Red

www.text.com/test.html?color=Black

www.text.com/test1.html?color=Black

www.text.com/test2.html?color=Black

我的最终代码:

$url_csv = "cache_build_urls_file.csv";
$url_csv_resource = fopen($url_csv,"r");
$color_csv = "colors_file.csv";
$color_csv_resource = fopen($color_csv,"r");
$new_color = "color_cache_build_urls_file.csv";
$outputBuffer = fopen($new_color, 'w');
$result = $urls = $colors = array();
if (($handle = fopen($url_csv, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $urls[] = $data[0];
}
fclose($handle);
}
if (($handle = fopen($color_csv, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $colors[] = $data[0];
 }
fclose($handle);
}
foreach( $urls as $url ) {
foreach( $colors as $color ) {
    $result[] = $url.'?color='.$color;
    }
}

foreach($result as $val) {
    $arr[0] = $val;
     fputcsv($outputBuffer,$arr);
}
fclose($outputBuffer);

我不打算向你解释一切,只是一些简单的基础知识。您要查找的是一个嵌套循环。基本上,您从读取第一个CSV文件开始,对于您获得的每个结果,您都会读取第二个文件。

如果CSV文件中的数据集很大,我可以建议首先将结果"缓存"到数组中。这将加快最终代码的操作速度。下面是一个快速示例:

$result = $urls = $colors = array();
if (($handle = fopen("source1.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $urls[] = $data[0];
    }
    fclose($handle);
}

我正在创建 2 个数组,一个用于 URL,一个用于颜色。然后我读取 CSV 文件并填充数组。第二个来源也会发生同样的事情。只要弄清楚自己在那里做什么。

然后,您将创建一个组合两个数组的嵌套循环:

foreach( $urls as $url ) {
    foreach( $colors as $color ) {
        $result[] = $url.'?color='.$color;
    }
}

现在,$result包含两个 CSV 中的数据的组合列表。此$result数组可以转换为 CSV。SO上有很多示例:将数组转换为csv