PHP 在 .csv 中重复时为 sku 添加前缀的脚本

PHP script for adding prefix to sku when duplicate in .csv

目前我有一个脚本,当它之前已经看到 sku 时,它会删除我的 csv 中的行。

这是脚本:

    <?php
// array to hold all unique lines
$lines = array();

// array to hold all unique SKU codes
$skus = array();

// index of the `sku` column
$skuIndex = -1;

// open the "save-file"
if (($saveHandle = fopen("unique.csv", "w")) !== false) {
    // open the csv file
    if (($readHandle = fopen("original.csv", "r")) !== false) {
        // read each line into an array
        while (($data = fgetcsv($readHandle, 8192, ",")) !== false) {
            if ($skuIndex == -1) {
                // we need to determine what column the "sku" is; this will identify
                // the "unique" rows
                foreach ($data as $index => $column) {
                    if ($column == 'sku') {
                        $skuIndex = $index;
                        break;
                    }
                }
                if ($skuIndex == -1) {
                    echo "Couldn't determine the SKU-column.";
                    die();
                }
                // write this line to the file
                fputcsv($saveHandle, $data);
            }

            // if the sku has been seen, skip it
            if (isset($skus[$data[$skuIndex]])) continue;
            $skus[$data[$skuIndex]] = true;

            // write this line to the file
            fputcsv($saveHandle, $data);
        }
        fclose($readHandle);
    }
    fclose($saveHandle);
}
?>

这很好用,但我开始需要已删除的内容。

我现在需要的是修改代码,为所有重复的 sku 添加相同的前缀,因为只有 2 个相同的 sku。

不知从何说起

为重复项添加前缀

这将为任何重复的 SKU 添加前缀,然后将其存储到唯一的 CSV 输出中,例如XYZ123 变成 duplicate-XYZ123.

变化:

if (isset($skus[$data[$skuIndex]])) continue;

至:

if (isset($skus[$data[$skuIndex]])) $data[$skuIndex] = 'duplicate-' . $data[$skuIndex];

修复重复的 header 行

if ($skuIndex == -1) {里面的fputcsv($saveHandle, $data);之后添加continue;。因为 fputcsv(...) 在循环中出现了两次,所以在循环的第一次迭代中会出现 运行 两次。