【问题标题】:Notice:Undefined offset注意:未定义的偏移量
【发布时间】:2015-08-01 13:09:22
【问题描述】:

我过去一直在使用这个脚本并且没问题。我将 txt 文件转换为 csv 并得到了一些未定义的错误。

function Importcsv($filename) { $row = 0;
$col = 0;

$handle = @fopen($filename, "r");
if ($handle) 
{
    while (($row = fgetcsv($handle, 4096)) !== false) 
    {
        if (empty($fields)) 
        {
            $fields = $row;
            continue;
        }

        foreach ($row as $k=>$value) 
        {
            $results[$col][$fields[$k]] = $value;
        }   
        $col++;
        unset($row);
    }
    if (!feof($handle)) 
    {
        echo "Error: unexpected fgets() failn";
    }
    fclose($handle);
}

return $results; }


$filename = "tm_data.csv";
$csvArray = Importcsv($filename);

foreach ($csvArray as $row)
{
 echo $row['CITY'];
}

如果您之前有任何想法或发现类似问题,请告诉我。

请查看几个错误行 注意:未定义的偏移量:/Applications/XAMPP/xamppfiles/htdocs/tm_marketing/index.php 第 20 行中的 386

注意:未定义的偏移量:第 20 行 /Applications/XAMPP/xamppfiles/htdocs/tm_marketing/index.php 中的 387

注意:未定义的偏移量:第 20 行 /Applications/XAMPP/xamppfiles/htdocs/tm_marketing/index.php 中的 388

注意:未定义的偏移量:第 20 行 /Applications/XAMPP/xamppfiles/htdocs/tm_marketing/index.php 中的 389

注意:未定义的偏移量:/Applications/XAMPP/xamppfiles/htdocs/tm_marketing/index.php 第 20 行中的 390

谢谢,

【问题讨论】:

  • 发布完整的错误消息,没有它我们无法帮助您。
  • 请看下面几行错误信息:注意:未定义的偏移量:386 in /Applications/XAMPP/xamppfiles/htdocs/tm_marketing/index.php on line 20 注意:未定义的偏移量:387 in /Applications /XAMPP/xamppfiles/htdocs/tm_marketing/index.php 在第 20 行 注意:未定义的偏移量:388 在 /Applications/XAMPP/xamppfiles/htdocs/tm_marketing/index.php 在第 20 行 注意:未定义的偏移量:389 在 /Applications/XAMPP /xamppfiles/htdocs/tm_marketing/index.php 第 20 行 注意:未定义的偏移量:/Applications/XAMPP/xamppfiles/htdocs/tm_marketing/index.php 第 20 行中的 390
  • @user4773611 在您的问题中包含错误。您可以通过编辑您的问题来做到这一点。

标签: php csv


【解决方案1】:

根据问题中发布的(缺乏)信息,我认为第 20 行是:

 $results[$col][$fields[$k]] = $value;

您的CSV 文件的第一行包含的列似乎少于数据行。

第一行(列名)存储在$fields 中,它有386 列。一些数据行包含超过 386 列(似乎是 391),对于以 386 开头的 $k$fields[$k] 未定义并触发您发布的通知。

解决方案取决于您。您可以通过添加缺少的列名或从有问题的行中删除额外的值来修复 CSV 文件。

您还可以修改代码以执行上述操作之一(即时生成一些列名或忽略额外的值)。

您还应该检查 CSV 文件是否正确编码。也许没有多余的列,fgetcsv() 错误地拆分了行。检查文件中使用的分隔符、引号和转义字符,并确保在对fgetcsv() 的调用中使用相同的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-27
    • 2012-02-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多