I have csv values like this:
$csv_data = \"test,this,thing
hi,there,this
is,cool,dude
have,fun\";
I want
Assuming every row in the CSV data has the same number of columns, this should work.
$lines = explode("\n", $csv_data);
$head = str_getcsv(array_shift($lines));
$array = array();
foreach ($lines as $line) {
$array[] = array_combine($head, str_getcsv($line));
}
If lines have a variable number of columns (as in your example, where the last line has 2 columns instead of 3), use this loop instead:
foreach ($lines as $line) {
$row = array_pad(str_getcsv($line), count($head), '');
$array[] = array_combine($head, $row);
}
Here is a complete solution:
$lines = explode("\n", $csv_data);
$formatting = explode(",", $lines[0]);
unset($lines[0]);
$results = array();
foreach ( $lines as $line ) {
$parsedLine = str_getcsv( $line, ',' );
$result = array();
foreach ( $formatting as $index => $caption ) {
if(isset($parsedLine[$index])) {
$result[$formatting[$index]] = trim($parsedLine[$index]);
} else {
$result[$formatting[$index]] = '';
}
}
$results[] = $result;
}
So what are we doing here?
explode
explode
and unset
)$results
)str_getcsv
Here is a very clean and simple solution:
function parse_row($row) {
return array_map('trim', explode(',', $row));
}
$rows = str_getcsv($csv_data, "\n");
$keys = parse_row(array_shift($rows));
$result = array();
foreach ($rows as $row) {
$row = parse_row($row);
$row = array_pad($row, 3, NULL);
$result[] = array_combine($keys, $row);
}