遍历csv文件并将每行与sql结果进行比较

vsdwdz23  于 2023-01-28  发布在  其他
关注(0)|答案(1)|浏览(152)

我下面的php代码允许我从数据库中获取当天的订单信息并将其保存在CSV文件中。这些数据包括订单的一般信息、客户信息和订购的产品。

<?php
require_once 'dbconfig.php';
try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);

    // SQL query that will search the database for the orders of the day (or here on the given date). The orders contain the information of the products etc..
    $sql = 'SELECT o.id_order ,c.id_customer, c.firstname, c.lastname, a.address1, a.address2, a.postcode, a.city,a.phone,c.email,a.phone_mobile, od.product_id,
od.product_name,od.product_quantity, od.product_price,o.total_paid_tax_incl, c.id_customer, op.date_add, op.amount, op.payment_method
FROM mod582_orders o
INNER JOIN mod582_customer c ON o.id_customer = c.id_customer
INNER JOIN mod582_address a ON o.id_address_delivery = a.id_address
INNER JOIN mod582_order_detail od ON o.id_order = od.id_order
INNER JOIN mod582_order_payment op ON o.reference = op.order_reference
WHERE CAST(o.date_add AS DATE) like "2022-12%";
';

    $r = $pdo->query($sql);
    $tab = [];
    $tab[] = ['ORDNOORDER', 'ORDREFCUSORDER', 'ORDNOCOSTNUMBER', 'ORDNOCUSTOMER', 'ORDCUSTOMERCODE', 'ORDCUSCAT', 'ORDTYPE', 'ORDCURRENCY', 'ORDCURRENCYRATE', 'ORDDESIGNATION',
        'ORDREPCODE', 'ORDPORT', 'ORDPORTTYPE', 'ORDPORTRATE', 'DEONOORDER', 'DEOCOMMENT', 'DEOCOUNTRY', 'DEONAME', 'DEOFIRSTNAME', 'DEOADDRESS1', 'DEOADDRESS2', 'DEOZIPCODE', 'DEOCITY',
        'DEOPHONE', 'DEOMAIL', 'DEOPHONEPORTABLE', 'ODLNOORDER', 'ODLNOORDERLINE', 'ODLNOARTICLE', 'ODLARTDESIGN', 'ODLQUANTITYORDER', 'ODLTTCCURUPRICE', 'ODLCODEPARCELLEFLEU',
        'PAYNUMPAYMENT', 'PAYNOCUSTOMER', 'PAYNOORDER', 'PAYNOCURRENCY', 'PAYDATEPAYMENT', 'PAYPAYMENTTTCCUR', 'PAYCURRENCYRATE', 'PAYCONTREPARTIE'];

    $odrline = 0; // start with zero, as incremented before first written out
    $prevordernumber = 0; // pick a number that is not a valid order number
// or empty string if not numeric
// Open the File
    $file = fopen("ArticlesStock.csv", "r");
    $i = 0;
// as long as is not end of file continue loop through

    while (!feof($file)) {
// get the file string by line
        $thisLine = fgets($file);
// Explode the line when there is  a  "; "
        $personData[$i] = explode(";", $thisLine);
        $i++;
    }
    // Number of Rows
    $numRows = sizeof($personData);
// Loop Through the Array
    $i = 1;
    $productID = 0;
    $productName = "";

    //Add the query result to the tab
    while ($rs = $r->fetch(PDO::FETCH_ASSOC)) {
        if ($prevordernumber != $rs['id_order']) //if the ID of the previous command is different from that of the current command
        {
            while ($i < $numRows) {
                if (str_contains($personData[$i][2], $rs['product_name'])) { //if the product name returned by the query is equal to a product name in the csv ArticleStock
                    $productName = $personData[$i][2]; //save the product name of the csv file ArticleStock in the variable
                    $productID = $personData[$i][0]; //save the product id of the csv file ArticleStock in the variable

                    $odrline++;
                    $baseDate = strtotime($rs['date_add']);
                    $formatDate = date("d/m/Y", $baseDate); //convert the date to appropriate format
                    $tab[] = [$rs['id_order'], $rs['id_order'], '17', '', 'AAA' . $rs['id_customer'], 'DET', 'O', 'EUR', '1', '', '115', 'D', 'P', '17', $rs['id_order'], '', 'FRA', $rs['firstname'],
                        $rs['lastname'], $rs['address1'], $rs['address2'], $rs['postcode'], $rs['city'], $rs['phone'], $rs['email'], $rs['phone_mobile'], $rs['id_order'], $odrline,
                        $productID, $productName, $rs['product_quantity'], $rs['product_price'], '', '', '', $rs['id_order'], 'EUR', $formatDate, $rs['amount'], '1', 'VIR'];
                    //we add the precedent variable on the final csv file
                    }
                $i++;
            }
        } else {//if the ID of the previous order is equal to that of the current order
            $tab[] = [$rs['id_order'], $rs['id_order'], '17', '', 'AAA' . $rs['id_customer'], 'DET', 'O', 'EUR', '1', '', '115', 'D', 'P', '17', $rs['id_order'], '', 'FRA', $rs['firstname'],
                $rs['lastname'], $rs['address1'], $rs['address2'], $rs['postcode'], $rs['city'], $rs['phone'], $rs['email'], $rs['phone_mobile'], $rs['id_order'], $odrline,
                $rs['product_id'], $rs['product_name'], $rs['product_quantity'], $rs['product_price'], '', '', '', $rs['id_order'], '', '', '', ''];
        }

        $prevordernumber = $rs['id_order'];
    }
    fclose($file); //Close the ArticlesStock CSV file
// write $tab to file
    $date = date('d-m-y');
    $fichier_csv = new SplFileObject('commandes_' . $date . '.csv', 'w'); //Save the final csv file
    foreach ($tab as $ligne) {
        $fichier_csv->fputcsv($ligne, ';');
    }

} catch (PDOException $e) {
    die("Could not connect to the database $dbname :" . $e->getMessage());
}

不过,我也有一个股票csv文件包含产品信息.(ID,产品名称,数量等.)
ArticleStock文件中存在的数据示例:

问题是数据库和股票csv文件之间的产品ID和名称不相同。
按要求退回产品的示例:

因此,当我的查询获取信息时,我需要比较返回的产品名称,以查看它们是否存在于ArticleStock文件中,如果是,则在最终的CSV文件中添加来自ArticleStock文件而不是来自SQL查询的产品名称和ID

lb3vh1jj

lb3vh1jj1#

问题简而言之:ProductID已损坏,因此我们需要比较产品名称。但是产品名称的格式不相似,并且部分文本不同:

database = "L'Enclos de Ramage 2014"
csv = "L'ENCLOS DE RAMAGE HAUT-MEDOC 2014"

当你面对一个大问题时,你需要分而治之。首先,我们可以把所有的东西都放到同一个大小写(小写):

database = database.lower()  # "l'enclos de ramage 2014"
csv = csv.lower()            # "l'enclos de ramage haut-medoc 2014"

然后,您就可以使用split进行真正的除法了(我没想到这会变成一个双关语):

import re
delimiters = "'", " "
regex_pattern = '|'.join(map(re.escape, delimiters))

database = re.split(regex_pattern, database) 
csv = re.split(regex_pattern, database) 

# Returns two lists:
# ['l', 'enclos', 'de', 'ramage', '2014']
# ['l', 'enclos', 'de', 'ramage', 'haut-medoc', '2014']

如果您可以确保数据库条目的字数始终少于csv条目,并且字数相同,则如果数据库条目包含另一个csv条目的每个单词,您就知道前者与后者相对应。

is_in_csv = [entry in csv for entry in database]
# [True, True, True, True, True]

all(is_in_csv)
# True (yes, all words in database are found in csv too!)

相关问题