解析 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
如您所见,一团糟。每个用户行下的注释与其相关,但不包含 "client ID".
等键
到目前为止,我的 PHP 这个 Laravel 应用程序是:
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,但在第二个循环中却找不到?我如何设置和保存这个值?
非常感谢
函数中声明的变量仅在该函数的范围内,您必须通过引用传递外部变量才能停止 "previous" 值,示例:
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();
我正在尝试解析用户信息的 CSV 文件。 CSV 格式如下:
userid,username,userlocation
notecontent, notedate
notecontent, notedate
notecontent, notedate
notecontent, notedate
userid,username,userlocation
notecontent, notedate
notecontent, notedate
如您所见,一团糟。每个用户行下的注释与其相关,但不包含 "client ID".
等键到目前为止,我的 PHP 这个 Laravel 应用程序是:
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,但在第二个循环中却找不到?我如何设置和保存这个值?
非常感谢
函数中声明的变量仅在该函数的范围内,您必须通过引用传递外部变量才能停止 "previous" 值,示例:
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();