2017-04-25 16 views
0

我正在从CSV文件获取数据并将其添加到数组中,以便将其保存到数据库中。这是阵列格式:PHP/PDO - 循环访问数组并将其添加到数据库的最佳方法

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]是相同的名称,我在我的数据库列:

enter image description here

所以,我想通过所有的数组循环,但跳过$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

回答

0

你可以放下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

+0

消费 “太多记忆”?怎么会这样? –

+0

因为你正在构建一个完整的数组;而只是重用一个变量。 –

+0

当我插入数据库时​​,应该使用如下数组:$ data [0],$ data [1],$ data [2]等等。 – oliverbj

相关问题