我想检查 csv 文件是否包含标题并忽略标题。

我必须检查第一列是否不是字符

csv 文件的格式为:平均温度、最低温度、最高温度

$f = fopen("./uploads/" .$filename, "r");
$string = "avgTemperature";
if (fgetcsv($f)==$string){  
    // read the first line and ignore it
    fgets($f);
}
有帮助吗?

解决方案

从您的评论开始,并且从实际数据是温度(即数字数据),如果您确实有标题,则它们将是文本字符串而不是数字。因此,您可以做到这样的事情:

$f = fopen("./uploads/" .$filename, "r");

if(!($data = fgetcsv($f))) {
    return;    //most likely empty file
}

if(!is_numeric($data[0])) {
    //this is your header line - skip it - and read the next line
    $data = fgetcsv($f);
}

while($data) {
    //process a line of data
    ...
    //and read the next line
    $data = fgetcsv($f);
}
.

编辑:最后一个循环的替代版本如下所示:

do {
    //process a line of data
    ...
}
while ($data = fgetcsv($f));
.

其他提示

我假设您的完整代码使用循环(while 或者 for).

因此,您有几种选择。

  • 只需跳过第一行 总是.
  • 使用逻辑来测试 标题行 然后跳过。

无论哪种方式, continue 是关键的一块。

PHP伪代码:

while (…) {
  if ($row == $header_row) {
    continue;
  }

  // data rows
}

更新

对于您的情况,确定第一行是否是标题行的逻辑似乎是更好的解决方案。您可以使用以下内容来测试这一点。

if ($row[0] == 'avgTemperature') {
  // header row
}

笔记: 这假设第一列数据是 平均温度 它的标题是 平均温度. 。根据需要进行调整。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top