php如何从csv文件转换数据?
我有一个csv文件,其中包含如下数据php如何从csv文件转换数据?,php,Php,我有一个csv文件,其中包含如下数据 shelfmark, centuries foo-0001, 2000s; bar-1234, 1200s, 1300s; baz-IK-1234, 0100s, 0200s, 0300s; and so on... 我想导入数据并将其转换为只有两列的格式: shelfmark, century foo-0001, 2000s; bar-1234, 1200s; bar-1234, 1300s; baz-IK-1234, 0100s; baz-IK-123
shelfmark, centuries
foo-0001, 2000s;
bar-1234, 1200s, 1300s;
baz-IK-1234, 0100s, 0200s, 0300s;
and so on...
我想导入数据并将其转换为只有两列的格式:
shelfmark, century
foo-0001, 2000s;
bar-1234, 1200s;
bar-1234, 1300s;
baz-IK-1234, 0100s;
baz-IK-1234, 0200s;
baz-IK-1234, 0300s;
and so on...
并将其写入新的csv文件中
如果一行包含超过一个世纪的值,我需要有关创建新行的代码的帮助
我的尝试:
<?php
$csv = array_map('str_getcsv', file($file));
array_walk($csv, function(&$a) use ($csv) {
// check if row has more than two column entries
if
// if so then split the first century value into a new row
// do so until no more century value is in the row left and continue with next row
$data = array_combine($csv[0], $a);
});
// write into new csv file
$fp = fopen('php://output', 'w');
foreach ( $data as $line ) {
$val = explode(",", $line);
fputcsv($fp, $val);
}
fclose($fp);
?>
您可以通过使用
array\u shift()
在最终内容上循环,只需去掉行标题('foo-0001'),然后将其添加到数组中的每个剩余元素,从而简化流程
这使用fwrite()
来维护内容格式
$csv = array_map('str_getcsv', file($file));
// Take the titles out of the main list of lines
$titles = array_shift($csv);
$fp = fopen('php://output', 'w');
// Add the header row
fwrite($fp, implode(",", $titles).PHP_EOL);
foreach ( $csv as $line ) {
$header = array_shift($line); // Remove the first part from the array
foreach ( $line as $entry ) {
fwrite($fp, $header.",". trim($entry,";").";".PHP_EOL);
}
}
fclose($fp);