php - 如何在php mysql中相对于列插入csv数组数据

标签 php mysql arrays csv

我想将不同 CSV 文件中的数据导入到 MySQL。 (不同的文件在不同的位置包含所需的列,但所有文件中的标题值相同)

一些 CSV 文件类似于;

-------------------------------------------------
|   Name, Father Name,  Contact, City, email,   |
-------------------------------------------------
|   Ali, Ahmed, 123456, isb. , ali@mail.com,    |
|   Fazi, Khan, 123456, hyd. , faiz@ymail.com,  |
-------------------------------------------------

有时 CSV 文件就像;

-------------------------------------------------
|   Name, Father Name,  Contact,  email, City,  |
-------------------------------------------------
|   Ali, Ahmed, 123456,  ali@mail.com,   isb. , |
|   Fazi, Khan, 123456,  faiz@ymail.com, hyd. , |
-------------------------------------------------

经过探索并研究了许多建议后,我得到了这个解决方案。 但我不知道如何使用此代码将数组行插入数据库中。

$names      = array('Name', 'Father Name', 'contact', 'email');
$picked     = array();
$theData    = array();
$isFirstRow = true;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $numCols = count($data);
    $row     = array();


    // first row to select columns for extraction
    if($isFirstRow) {
        for($c=0; $c<$numCols; $c++)
            if(!in_array($data[$c], $names)
                continue;
            else
                $picked[] = $c;
        $isFirstRow = false;
    }

    // process remaining rows
    else {
        for($c=0; $c < $numCols; $c++)
            if(in_array($c, $picked))
                $row[] = $data[$c];
        $theData[] = $row;
    }

  }
fclose($handle);
}

请帮我看看如何根据$names[]在MySQL中插入$theData[]的数据。 提前谢谢您:)

最佳答案

我已经多次与这个问题作斗争,我想出的最通用的解决方案是将您的已知字段“映射”到 CSV 中代表该字段的列。

下面是您的代码(已修改),带有注释,用于解释该过程。

请注意,此例程要求 CSV 的第一行包含字段名称,并且它们与您所需的字段名称相匹配。

$names      = array( 'Name', 'Father Name', 'contact', 'email' );
$picked     = array();
$theData    = array();
// new array to store the "mapping"
$map        = array();

$handle = fopen("test.csv", "r");
if ( FALSE !== $handle ) {
    // get the first row
    $row = fgetcsv( $handle, 1000, ',');

    // loop over desired fields, assign the column index to map array
    foreach( $names AS $name ) {
        // array_search will find the field name in the row array and return the index
        // note: this is a case-insensitive array-search
        // see this Q&A for more info: https://stackoverflow.com/a/4170079/870729
        $index = array_search( strtolower( $name ), array_map( 'strtolower', $row ) );
        if ( FALSE !== $index ) {
             $map[ $index ] = $name;
        }
    }

    // if not all fields present, error and exit
    if ( count( $map ) < count( $names ) ) {
         echo 'All fields must be present: ' . implode( ', ', $names );
         die();
    }

    while ( $data = fgetcsv($handle, 1000, "," ) ) {
        $row     = array();

        // loop over known fields / index and assign to record
        foreach( $map AS $index => $field ) {
             // $index is the column number / index
             // $field is the name of the field
             $row[ $field ] = $data[ $index ];
        }    

        $theData[] = $row;
    }

    fclose($handle);
}

现在,当您查看 $theData 时,它应该包含完整的“字段映射”,因此您可以根据这些字段名称插入每一行:

示例:

var_dump( $theData[0] );

会产生类似这样的结果:

array(
    'Name'        => 'Ali',
    'Contact'     => '123456',
    'Father Name' => 'Ahmed',
    'email'       => 'ali@mail.com'
    'City'        => 'isb.'
);

无论 CSV 中的列的顺序如何。

关于php - 如何在php mysql中相对于列插入csv数组数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44850744/

相关文章:

php - jquery ajax 返回值没有按预期响应

php - Yii2 数据库 session - 存储附加属性和用户信息

MySQL 语法 - IF/END IF

mysql - 将 MS Access 查询转换为 MariaDB

php - 如何使用 array_count_values() 和 mySQL 来统计值的出现次数

javascript - JQuery对话框内容打开后清空

php - 注销脚本不起作用

PHP date_default_timezone_set() 距 GMT 偏移量是否可能?

Javascript:从属性匹配但没有 forEach 的数组中删除前 X 项?

c - 随后的 printf 语句破坏了不相关的数组