【问题标题】:Access variable name from the previous loop when parsing CSV file解析 CSV 文件时从上一个循环访问变量名
【发布时间】:2016-04-25 14:13:16
【问题描述】:

我正在尝试解析用户信息的 CSV 文件。 CSV 格式如下:

userid,username,userlocation
notecontent, notedate
notecontent, notedate
notecontent, notedate
notecontent, notedate
userid,username,userlocation
notecontent, notedate
notecontent, notedate

如您所见,这是一团糟。每个用户行下的注释与其相关,但不包含诸如“客户 ID”之类的键。

到目前为止,这个 Laravel 应用程序的 PHP 是:

Excel::load("storage/app/notes.csv", function($reader) {
    $reader->each(function($row) { //Loop through row by row

        if (strlen($row->client_id) == 5) {
            $loopclient = $row->client_id;
            $this->line('client'.$loopclient);
        } else {
            //Our note should have client ID of loopclient
            $this->info($loopclient.": ".$row->client_id);
        }

    });
 })->get();

我通过查看单元格是否为 5 个字符长来检查行是注释还是 ID。如果是,我想设置 $loopid 并移动到下一行。然后,如果检查显示该行是便笺,则 $loopid var 应该始终是最近一个客户端的 ID。

有谁知道为什么这行不通,或者有更好的方法吗?

我收到以下错误:

Undefined variable: loopclient

它在第一个循环中找到了 ID,但在第二个循环中不可用?如何设置和保存这个值?

非常感谢

【问题讨论】:

    标签: php laravel csv phpexcel laravel-excel


    【解决方案1】:

    在函数中声明的变量仅在该函数的范围内,您必须通过引用传递外部变量才能停止“先前”值,例如:

    Excel::load("storage/app/notes.csv", function($reader) {
        $loopclient = -1; //Or proper initial value
        $reader->each(function($row) use (&$loopclient) { //Loop through row by row
    
            if (strlen($row->client_id) == 5) {
                $loopclient = $row->client_id;
                $this->line('client'.$loopclient);
            } else {
                //Our note should have client ID of loopclient
                $this->info($loopclient.": ".$row->client_id);
            }
    
        });
     })->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-09
      • 1970-01-01
      相关资源
      最近更新 更多