我需要将数组的ID与CSV文件的行ID匹配,如果匹配,则从CSV文件中删除该特定行,否则文件数据将保持不变。
代码如下:
if (($handle = fopen("$filename_with_path", "w")) !== FALSE)
{
while (($data[1] = fgetcsv($handle, 1000, ",")) !== FALSE)
{
if(in_array($data[1],$del_tag_array)){
unset($data);
} else {
$tag_data_from_csv[]=$data;
}
}
fclose($handle);
}
foreach ($tag_data_from_csv as $data_at_each_index)
{
fputcsv($file_pointer, $data_at_each_index) or die('cannot write file');
}
CSV文件记录:
row1 = 1,714,pictures,222
row2 = 1,713,unique,222
如果713 = 713,则应从CSV中删除带有713的行
答案 0 :(得分:0)
这样的事情怎么办?
#!/usr/bin/env php
<?php
$filename_with_path = '/tmp/input.csv';
$del_tag_array = [713];
$tag_data_from_csv = [];
if ($handle = fopen($filename_with_path, "r")) {
while ($data = fgetcsv($handle, 1000, ",")) {
if (in_array($data[1], $del_tag_array)){
continue;
}
$tag_data_from_csv[] = $data;
}
}
fclose($handle);
if ($handle = fopen($filename_with_path, "w")) {
foreach ($tag_data_from_csv as $data_at_each_index)
{
fputcsv($handle, $data_at_each_index) or die('cannot write file');
}
}
fclose($handle);
棘手的部分是:
'w'
打开,您只需将其擦除,因此没有行可读取)