-1

我正在处理 Magento 产品 csv 文件,我有一个包含 3 列的 csv 文件,例如

<pre>Name, description, Color</pre>
<pre>t-shirt, tshirt description, "green, blue, yellow"</pre>

现在基于第 3 列(颜色)的值,我想在单独的文件中输出每一行,以某种方式说“new_products.csv”,这样生成的文件就像

<p>Name, description, Color</p>
<pre>t-shirt, tshirt description, green</pre>
<pre>t-shirt, tshirt description, blue</pre>
<pre>t-shirt, tshirt description, yellow</pre>

我从这段代码开始

$row = 1;

if (($handle = fopen("product.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $num = count($data);
            $name = $data[0];
    $desc = $data[1];

    for ($c=0; $c < $num; $c++) {


        $fp = fopen('new_products.csv', 'w');

        if($c == 2){ //if we are at color field
            $color = explode(',', $data[$c]);
            $color_count = count($color);
            for($i=0; $i<$color_count; $i++){

                fputcsv($fp, array($name,$desc,$color[$i]));
            }

        }

    }
            $row++;
}
fclose($handle);
}

但是上面的代码只输出最后一行。

谢谢

4

1 回答 1

3

最后我已经能够找到我自己的解决方案。实际上需要在文件末尾设置文件指针。

$row = 1;

if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $num = count($data);
    $name = $data[0];
    $desc = $data[1];


    for ($c=0; $c < $num; $c++) {            

        if($c == 2){ //if we are at color field
          $fp = fopen('file.csv', 'a'); //Open for writing only; place the file pointer at the end of the file.
            $color = explode(',', $data[$c]);
            $color_count = count($color);
            for($i=0; $i<$color_count; $i++){
                fputcsv($fp, array($name,$desc,$color[$i]));
            }
            fclose($fp);
        }

    }

            $row++;
}
fclose($handle);

}

于 2013-03-25T09:35:42.147 回答