我正在从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
     )
 )

最佳答案

请尝试以下代码:

//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);

关于php - 如何基于第一个数组列名称在数据库表中插入数组值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12000332/

10-14 15:58
查看更多