Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSV data to array_map and str_getcsv using delimiter

Tags:

php

My problem is I'm unable to pass 2nd parameter to str_getcsv function.

$rows   = array_map('str_getcsv', file($filePath_product_names_t), [";"]); 
            $header = array_shift($rows);
            $csv    = [];
            foreach($rows as $row) {
                $csv[] = array_combine($header, $row);
            }

CSV structure

"25";"some text"; "also some Text"

And also getting WARNING:

array_combine(): Both parameters should have an equal number of elements

like image 983
Engazan Avatar asked Jun 15 '18 06:06

Engazan


2 Answers

Try this:

$rows = array_map(function($v){return str_getcsv($v, ";");}, file($filePath_product_names_t));
$header = array_shift($rows);
$csv    = [];
foreach($rows as $row) {
    $csv[] = array_combine($header, $row);
}
print_r($rows);
like image 154
Mawia HL Avatar answered Nov 15 '22 23:11

Mawia HL


Combining the two problems, the first is that you can't pass a parameter the way you are trying in the array_map() so as in the link I posted in the comments, you can create an anonymous function to do this.

The second is that, in some cases a CSV file doesn't always have all the data for a row in the file. In this case the header row and the other rows don't have the same amount of data, so use array_pad() to add blanks to make sure they do have the same length. To combine these into the code...

$rows   = array_map(function($data) { return str_getcsv($data,";");}
    , file($filePath_product_names_t));
$header = array_shift($rows);
$csv    = [];
foreach($rows as $row) {
    $row = array_pad($row, count($header), "");
    $csv[] = array_combine($header, $row);
}

print_r($csv);
like image 43
Nigel Ren Avatar answered Nov 15 '22 21:11

Nigel Ren