合并 csv 文件中的 2 行并创建一个新的 CSV 来存储合并后的数据 PHP?

Merge 2 rows in csv file and creating a new CSV to store the merged data with PHP?

美好的一天。我有一个结构如下的 csv 文件

Id |    ArticleId  | LanguageId | Title             | Content
----------------------------------------------------------------------
1         2              1        Francais Title    Francais Content
2         2              2        English Title      English Content

如何将文章合并到我的预期结果中? Expect(注意:[:fr] 和 [:en] 是 q-translate wordpress 的简码,我只需要定义它以便我可以导入数据库)

ArticleId     | Title                       | Content
------------------------------------------------------------------
      2       |  [:fr]Francais Title[:en]  |   [:fr]Francais Content
              |   English Title            |    [:en]English Content

生成文件中我当前的 php 代码。

<?php 
$row = 1;
if (($handle = fopen("dbo.ArticleTranslation.csv", "r")) !== FALSE) {
    $query = '';
    $flag = true;
    while (($data = fgetcsv($handle, 2000, ",")) !== FALSE) {
        if($flag) { $flag = false; continue; }
        $num = count($data);

        $content = '';
        $title = '';

        if ($data[2] == '1') {
            $content .= '[:fr]' . $data[4];
            $title .= '[:fr]' . $data[3];

        } else {
            $title .= '[:en]' . $data[3];
            $content .= '[:en]' . $data[4];
        }
        //ie(var_dump($content));
        //var_dump($content);

       var_dump($data);

        $row++;
       // var_dump($mergeContent);
    }
    fclose($handle);
} 
?>

这是一个解决方案:首先您必须创建一个空数组来包含提取的数据。然后,您遍历 csv 行。对于每一行,您提取文章数据。如果该文章已经存在,您只需将 lang 附加到数组即可。如果不是,则将文章创建到结果数组中。

if (($handle = fopen("dbo.ArticleTranslation.csv", "r")) !== false) {
    $extractedData = [];
    fgetcsv($handle, 2000, ","); // skip first line
    while (($line = fgetcsv($handle, 2000, ",")) !== false) {
        $articleId = $line[1];
        $lang = $line[2];
        $title = $line[3];
        $content = $line[4];

        // convert lang id to code
        if ($lang == 1) $lang = '[:fr]';
        if ($lang == 2) $lang = '[:en]';

        // build string with lang code
        $content = $lang.$content;
        $title = $lang.$title;

        // check if an article with this id was already extracted
        if (array_key_exists($articleId, $extractedData)) {
            // append lang to existing article
            $extractedData[$articleId]['Content'] .= $content;
            $extractedData[$articleId]['Title'] .= $title;
        } else {
            // add new article
            $extractedData[$articleId] = [
                'ArticleId' => $articleId,
                'Content' => $content,
                'Title' => $title
            ];
        }
    }
    fclose($handle);
}