【发布时间】:2013-09-22 05:07:48
【问题描述】:
我从 csv 文件中读取了以下数组:
Array
(
[0] => Array
(
[0] => book1
[1] => description1
[2] => category1
[3] => code1
[4] => editor1
[5] => 0
[6] => eur
[7] => out of stoc
)
[1] => Array
(
[0] => book2
[1] => description2
[2] => category2
[3] => code2
[4] => editor2
[5] => 0
[6] => curr2
[7] => out of stoc
)
[2] => Array
(
[0] => book3
[1] => description3
[2] => category3
[3] => code3
[4] => editor3
[5] => 0
[6] => curr3
[7] => out of stoc
)
)
代码:
function read_CSV_raza($rzs_csv) {
$file_handle = fopen($rzs_csv, 'r');
while (!feof($file_handle)) {
$line_of_text[] = fgetcsv($file_handle, 1024, ';');
}
fclose($file_handle);
return $line_of_text;
}
$rzs_csv = 'rzs.csv';
$csv = read_CSV_raza($rzs_csv);
我想添加另一个数组(标题),以便将此介绍写入另一个 csv 文件。 前:
Array
(
[0] => Array
(
[0] => h1
[1] => h2
[2] => h3
[3] => h4
[4] => h5
[5] => h6
[6] => h7
[7] => h8
)
[1] => Array
(
[0] => book1
[1] => description1
[2] => category1
[3] => code1
[4] => editor1
[5] => 0
[6] => eur
[7] => out of stoc
)
[2] => Array
(
[0] => book2
[1] => description2
[2] => category2
[3] => code2
[4] => editor2
[5] => 0
[6] => curr2
[7] => out of stoc
)
[3] => Array
(
[0] => book3
[1] => description3
[2] => category3
[3] => code3
[4] => editor3
[5] => 0
[6] => curr3
[7] => out of stoc
)
)
我尝试使用 array_merge(); array_unshift();但无济于事,我没有得到我需要的结果。
在新的 CSV 中写入数组的代码是:
$fp = fopen('rezultate.csv', 'w') or die("Can't open rezultate.csv");
foreach ($csv as $items) {
fputcsv($fp, $items, ';', '"');
}
fclose($fp) or die("Can't close rezultate.csv");
由于我不是程序员,因此我们将不胜感激。
【问题讨论】:
-
只需在
foreach ($csv as $items)循环之前立即执行fputcsv($fp, $headers, ';', '"');...。它比 array_unshift() 更有效 -
刚刚做了,但现在它只写入标题而不是数组
-
$fp = fopen('rezultate.csv', 'w') or die("Can't open rezultate.csv"); fputcsv($fp, $headers, ';', '"'); foreach ($csv as $items) { fputcsv($fp, $items, ';', '"'); } fclose($fp) or die("Can't close rezultate.csv"); -
非常感谢您像梦一样工作!
标签: php arrays csv multidimensional-array