解析 CSV 文件时访问上一个循环中的变量名称


Access variable name from the previous loop when parsing CSV file

我正在尝试解析用户信息的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,但在第二个循环中不可用?如何设置和保存此值?

非常感谢

函数中声明的变量仅在该函数的作用域内,您必须通过引用传递外部变量才能停止"上一个"值,例如:

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();