【问题标题】:PHP/PDO - Best way to loop through an array and adding it to a databasePHP/PDO - 循环遍历数组并将其添加到数据库的最佳方法
【发布时间】:2017-04-25 12:44:43
【问题描述】:

我正在从 CSV 文件中获取数据并将其添加到数组中,以便将其保存到我的数据库中。这是数组格式:

Array
(
    [0] => Array
        (
            [0] => Product code
            [1] => Product text
            [2] => Stockcode
            [3] => Origin
            [4] => Batchnumber
            [5] => Quantity
        )

    [1] => Array
        (
            [0] => 02-018              
            [1] => TEMPCELL13 TIF 120 HOUR 6P/P  
            [2] => OK1
            [3] =>    
            [4] =>                  
            [5] => 13
        )

    [2] => Array
        (
            [0] => 02-038              
            [1] => TEMPCELL60 TIF 120 HOUR(BROWN)
            [2] => OK1
            [3] =>    
            [4] =>                  
            [5] => 15
        )
)

其中,$data[0] 与我数据库中的列同名:

所以,我想遍历所有数组,但跳过$data[0],并将其添加到我的数据库中。这是我目前拥有的:

function process_csv($file) {

    $file = fopen($file, "r");
    $data = array();

    while (!feof($file)) {
        $data[] = fgetcsv($file,null,';');
    }

    fclose($file);

    unset($data[0]); //Unset the header information, since we only want the values to parse into our inventory database. $data[0] contains the header from the CSV = columns in our database
    foreach($data as $insert){

    //Insert $data to my database
    // $insert[] now holds the array

    }

}

循环遍历每个数组并添加它的最佳方法是什么?此外,如果“product_code”已经存在于数据库中,那么它应该只是UPDATE该行。

【问题讨论】:

    标签: php mysql arrays pdo


    【解决方案1】:

    您可以删除foreach 语句并将您的逻辑直接移动到while 循环中:

    $header = true;
    while (!feof($file)) {
        $data = fgetcsv($file,null,';');
    
        // skip the first line
        if ($header) {
            $header = false;
        }
        else {
            //Insert $data to my database
        }
    }
    

    否则,您将循环两次(while 逐行读取文件,foreach 循环数组)并消耗太多内存来构建数组以进行循环。

    对于 SQL,您可以使用 INSERT ... ON DUPLICATE KEY UPDATE 语句:https://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html

    【讨论】:

    • 消耗“太多内存”?怎么样?
    • 因为你正在构建一个完整的数组;而是只重用一个变量。
    • 当我插入数据库时​​,我应该使用如下数组:$data[0]、$data[1]、$data[2] 等?
    • 如果我使用这样的数组,插入数据库: $stmt->bindParam(":product_code", $data[0]); - 我知道“列 'product_code' 不能为空”
    • $datawhile 循环中看起来像Array ( [0] => 02-038 [1] => TEMPCELL60 TIF 120 HOUR(BROWN) [2] => OK1 [3] => [4] => [5] => 15 )
    猜你喜欢
    • 1970-01-01
    • 2018-04-07
    • 2016-01-14
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 2014-01-07
    • 1970-01-01
    相关资源
    最近更新 更多