首页 > 解决方案 > 未定义索引:id,意外行为

问题描述

我在 laravel 的控制台命令中处理 CSV 文件。我知道有用于导入 CSV 文件的库,但是我遇到了一个奇怪的未定义索引错误,我希望有人可以了解更多信息。如果没有这个专栏,我可以实现我所需要的,但我很好奇为什么会发生这个错误。

public function handle()
    {
        $file = Storage::disk('local')->get('upload.csv');

        $lines = explode("\r\n", $file);

        $keys = [];

        foreach ($lines as $key => $line)
        {

            $outputLine = [];

            if($key == 0)
            {
                // Get header columns
                $keys = str_getcsv($line); continue;
            }

            // Get row contents
            $items = str_getcsv($line);

            foreach ($items as $k => $item)
            {
                // Rename keys to match headers
                $outputLine[$keys[$k]] = $item;
            }
                // try to access $outputLine['id']
                // error: Undefined Index: id

            $csv[$key] = $outputLine;
        }

    }

然而,输出$csv[$key] 清楚地显示了 csv 中所有条目的键 ['id']。尝试访问这里也会引发同样的问题。访问数组中的任何其他任意键都可以正常工作。无论名称如何,它始终是第一个键。

更新:提供 CSV 导入示例

id,name,email,membership_id
1,John,John@example.com,1
2,Jane,Jane@example.com,2
3,Brian,Brian@example.com,3

更新 2:提供 $items 的转储

array:4 [
  0 => "1"
  1 => "John"
  2 => "john@example.com"
  3 => "1"
]
array:4 [
  0 => "2"
  1 => "Jane"
  2 => "jane@example.com"
  3 => "2"
]
array:4 [
  0 => "3"
  1 => "Brian"
  2 => "brian@example.com"
  3 => "3"
]
array:4 [
  0 => "4"
  1 => "Adam"
  2 => "adam@example.com"
  3 => "4"
]
array:4 [
  0 => "5"
  1 => "Frank"
  2 => "frank@example.com"
  3 => "5"
]
array:4 [
  0 => "6"
  1 => "Phil"
  2 => "phil@example.com"
  3 => "6"
]

转储$outputLine

array:4 [
  "id" => "1"
  "name" => "John"
  "email" => "john@example.com"
  "membership_id" => "1"
]
array:4 [
  "id" => "2"
  "name" => "Jane"
  "email" => "jane@example.com"
  "membership_id" => "2"
]
array:4 [
  "id" => "3"
  "name" => "Brian"
  "email" => "brian@example.com"
  "membership_id" => "3"
]
array:4 [
  "id" => "4"
  "name" => "Adam"
  "email" => "adam@example.com"
  "membership_id" => "4"
]
array:4 [
  "id" => "5"
  "name" => "Frank"
  "email" => "frank@example.com"
  "membership_id" => "5"
]
array:4 [
  "id" => "6"
  "name" => "Phil"
  "email" => "phil@example.com"
  "membership_id" => "6"
]

标签: phplaravel

解决方案


我认为您没有,在 CSV 中使用默认分隔符

https://www.php.net/manual/en/function.str-getcsv.php

尝试根据输入文件中的内容设置正确的

str_getcsv($line, ';') // example with ';' delimiter

推荐阅读