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]
是相同的名称,我在我的数据库列:
所以,我想通过所有的数组循环,但跳过$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
。
消费 “太多记忆”?怎么会这样? –
因为你正在构建一个完整的数组;而只是重用一个变量。 –
当我插入数据库时,应该使用如下数组:$ data [0],$ data [1],$ data [2]等等。 – oliverbj