gpt4 book ai didi

php - 具有多个标题行的 CSV;使用php导入mysql

转载 作者:行者123 更新时间:2023-11-29 02:07:33 25 4
gpt4 key购买 nike

我有一个 CSV 文件,里面有两组数据 [它是一个温度记录器]。我想知道是否有办法将前两行导入为一组数据,将其余行导入为第二组数据。我熟悉 PHP,但从来没有做过这样的事情。我在下面附上了一部分数据。任何帮助或指导将不胜感激。谢谢。

阿杰

Serial Number,Model,Name,Number,Time of Reading,Sample Rate,Start Time
910000000ebeaa4,DS1922T,SRBA04-240909 ,beaa-TNTVLPRP54,9/30/09 16:52,1,9/24/09 18:59
Sample #,Date/Time,Temp ¡F,Temp ¡C,,,
1,"Thu, Sep, 24, 06:59, PM",82.4,28,,,
2,"Thu, Sep, 24, 07:00, PM",83.3,28.5,,,
3,"Thu, Sep, 24, 07:01, PM",83.3,28.5,,,
4,"Thu, Sep, 24, 07:02, PM",83.3,28.5,,,
5,"Thu, Sep, 24, 07:03, PM",83.3,28.5,,,
6,"Thu, Sep, 24, 07:04, PM",83.3,28.5,,,
7,"Thu, Sep, 24, 07:05, PM",83.3,28.5,,,
8,"Thu, Sep, 24, 07:06, PM",83.3,28.5,,,
9,"Thu, Sep, 24, 07:07, PM",83.3,28.5,,,
10,"Thu, Sep, 24, 07:08, PM",83.3,28.5,,,

解决方案,基于 deceze 下面的评论

deceze,谢谢。这有效[与 sql 插入一样]。非常感谢。

<?php
$fhandle = fopen('1.csv', 'r');

$device_header = fgetcsv($fhandle, 1000, ',');
$device_data = fgetcsv($fhandle,1000,',');

$device = array_combine($device_header, $device_data);

$data_header = fgetcsv($fhandle,1000,',');

$dataset = array();
while ($data = fgetcsv($fhandle,1000,',')) {
$dataset[] = array_combine($data_header, $data);
}

fclose($fhandle);

?>

最佳答案

应该这样做:

$fhandle = fopen('/path/to/input.csv', 'r');

$headers = fgetcsv($fhandle); // reads first line
$set1 = array_combine($headers, fgetcsv($fhandle)); // reads second line

$set2 = array();
$headers = fgetcsv($fhandle); // reads third line
while ($data = fgetcsv($fhandle)) { // reads all following lines
$set2[] = array_combine($headers, $data);
}

fclose($fhandle);

/*
$set1 == array('Serial Number' => '910000000ebeaa4', 'Model' => ...);
$set2 == array(
array('Sample #' => 1, 'Date/Time' => 'Thu, Sep, 24, 06:59, PM', ...),
...
);
*/

关于php - 具有多个标题行的 CSV;使用php导入mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3315070/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com