1

我正在开发一个读取配置文件的 cron 作业,该配置文件具有一些 json 格式的配置,而且我有一个 csv 文件,我必须从中将数据插入 mysql tanble
我已经完成了它的第一部分,即读取配置文件并读取csv 文件
现在的问题是我必须在 csv 中搜索配置文件中的 mysql 列,然后如果在 csv 中找到匹配列,则必须将该列中的值插入到 mysql 表中。
我被这部分卡住了,需要一些帮助来完成这个。
这是示例配置文件,我必须在 csv 中搜索源,并且必须将其放入 csv 的 detination 列。

"matchingField": [
            {
                "source": "ProductLongDescription",
                "detination": "Description"
            },
            {
                "source": "ExtraTextOne",
                "detination": "EventDate"
            },
            {
                "source": "ExtraTextTwo",
                "detination": "EventTime"
            },
            {
                "source": "ExtraTextThree",
                "detination": "LocationInfo"
            },
            {
                "source": "Zupid",
                "detination": "Unique_ID"
            },
            {
                "source": "ProductName",
                "detination": "Title"
            },
            {
                "source": "ProductPrice",
                "detination": "Price"
            },
            {
                "source": "MerchantProductCategory",
                "detination": "Category"
            },
            {
                "source": "ImageMediumURL",
                "detination": "ExternalImageUrl"
            },
            {
                "source": "ProductManufacturerBrand",
                "detination": "LocationName"
            },
            {
                "source": "ZanoxProductLink",
                "detination": "RedirectLink"
            },
            {
                "source": "TermsOfContract",
                "detination": "sittingType"
            }
        ]
4

1 回答 1

0

我自己得到了解决方案:)。首先为源列和目标列创建两个数组,然后为 csv 标题列创建一个数组,然后在源数组中搜索标题列值,如果找到匹配项,则创建一个包含目标列名称及其来自 csv 的相应值的查询. 可能 bi 没有很好地解释代码,但这解决了我的问题。

while ( ($data = fgetcsv($handle, 10000, $columnDelimiter) ) !== FALSE )
{
    $number_of_fields = count($data);
    if ($current_row == 1)
    {
    //Header line
        for ($c=0; $c < $number_of_fields; $c++)
        {
            $header_array[$c] = $data[$c];
        }
    }
    else
    {
    //Data line
        $sql_str = '';
        for ($c=0; $c < $number_of_fields; $c++)
        {
            if($key = array_search($header_array[$c],$source_arr)){
                $sql_str .= $dest_arr[$key]." = '".$data[$c]."',";
             }
        }
        $sql_str = "INSERT INTO $destinationTable SET ".trim($sql_str,',');
        mysql_query($sql_str);
    }
    $current_row++;
}
于 2013-10-10T10:46:13.520 回答