samiles samiles - 7 months ago 15
PHP Question

Access variable name from the previous loop when parsing CSV file

I am trying to parse a CSV file of user information. The CSV is formatted at such:

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


As you can see it is a mess. The notes under each user row relate to it, but contain no key such as "client ID".

My PHP so far for this Laravel app is:

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


I check if row is a note or ID by seeing if the cell is 5 chars long. If it is, I wanted to set $loopid and move to the next row. Then, if the check shows the row is a note, the $loopid var should always be the ID of the most previous client.

Does anyone know why this won't work, or a better way to do it?

I get an error of:

Undefined variable: loopclient


It finds the ID on the first loop, but is not available on the second one? How can I set and save this value?

Many thanks

Answer

Variables declared in a function are only in scope within that function, you have to pass an external variable by reference to be able to stop a "previous" value, example:

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