我需要检查csv文件的第一行,看看它是否包含列(数字、名称、金额)的标题。如果第一行包含这些标题,则退出文件,或者如果第一行不包含此信息,则添加数字、名称和金额。
我试着检查第一列,第一行是否包含一个数字,这意味着没有标题。
这是我使用的代码。再次感谢您的帮助。
$rows = $phones = [];
if (($handle = fopen($file_tmp, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
list($phone, $name, $amount) = $data;
if(!($data = fgetcsv($handle))) {
return; //most likely empty file
}
if(!is_numeric($data[0])) {
fputcsv($handle, array('number', 'name', 'amount'));
}
$phone = str_replace(['(',')','-'], '', $phone);
$amount = str_replace(['$'], "", $amount);
$amount = sprintf('$%.2f', $amount);
// track unique phone numbers here
if (isset($phones[$phone])) {
// it's a duplicate so just ignore the entire row
continue;
}
// otherwise it's a new phone number so store it
$phones[$phone] = true;
$rows[] = [$phone, $name, $amount];
// or output directly
//echo "$phone | $name | $amount";
}
fclose($handle);
}
您有两个选项可供选择:
- 修正了加载程序/导出程序中使用或不使用CSV导出标头的规则
- 固定列顺序;知道
amount
字段的格式,您可以检查该值是否对任何行有效
在PHP中将"$100.00"解析为数字:
NumberFormatter::parseCurrency