未定义索引:ID,意外行为

时间:2019-06-26 09:33:10

标签: php laravel

我正在为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"
]

1 个答案:

答案 0 :(得分:0)

我认为您没有在CSV中使用默认的定界符,

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

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

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