0

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

非常感谢

4

1 回答 1

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();
于 2016-04-25T14:28:40.583 回答