1

我正在从 csv 文件导入数据,所以我使用了该代码

<?php
$path = "Export.csv";
$row = 1;
if (($handle = fopen($path, "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $row++;
        $data_entries[] = $data ;


    }
    fclose($handle);
}
 echo"<pre>";
 print_r($data_entries);
 echo"</pre>";
?>

我的数组输出就像我的第一个数组显示列名之后所有数组都显示值所以我想根据第一个数组列名插入值

 Array
 (
  [0] => Array
    (
        [0] => Type
        [1] => PinCode
        [2] => APN
        [3] => County
    )
  [1] => Array
    (
        [0] => Auction
        [1] => 503082537
        [2] => 502-052-002
        [3] => United States of America
    )
  [2] => Array
    (
        [0] => Auction
        [1] => 21596378
        [2] => 628-202-038
        [3] => Australia
     )
 )
4

2 回答 2

3

试试下面的代码:

//extract the column names
$fields = array_shift($data_entries);
$values = array();

// Append the values
foreach($data_entries as $value){
   $values[]="('{$value[0]}', '{$value[1]}', '{$value[2]}', '{$value[3]}' )";
}

// Build the SQL
$sql = "INSERT INTO `TABLE_NAME` (" . implode(',' , $fields) . ") values " . implode(',', $values);
于 2012-08-17T06:09:48.190 回答
0

您可以尝试不同的方法,因为您的数据来自 CSV 文件。

LOAD DATA LOCAL INFILE 'Export.csv' INTO TABLE YourTable;

有很多选项,请阅读手册:http ://dev.mysql.com/doc/refman/5.0/en/load-data.html

于 2012-08-17T06:06:22.977 回答