【问题标题】:Undefined index: id, unexpected behaviour未定义索引:id,意外行为
【发布时间】:2019-06-26 18:00:56
【问题描述】:

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

【问题讨论】:

  • 该 CSV 文件的外观如何?也许您使用了不同的分隔符?
  • 我提供了一个简化的 CSV 示例。
  • 谢谢。此外,如果您可以在 foreach ($items as $k => $item) 循环之前提供转储,这可能会有所帮助。你从var_dump($keys, $items); 得到什么?
  • 我已将转储添加为编辑
  • 谢谢。看起来不错。您确定要在此foreach ($items as $k => $item) 之后访问$outputLine['id']

标签: php laravel


【解决方案1】:

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

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

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

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

【讨论】:

  • 嗨 Lucas,对不起,我应该提供我的 CSV 的 sn-p,CSV 确实是逗号分隔的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-01
  • 2013-11-27
  • 2015-06-02
  • 2021-09-08
  • 1970-01-01
相关资源
最近更新 更多