I have a project going on and this is the first time I've encountered CSV. I've read numerous post but haven't found what I need.
So we have and CSV with values like this
Name,Country,Color,Pet
David,UK,Red,Dog
Andy,USA,Blue,Cat,Dog,Fish
...
So sometimes there are multiple values on "Pet", and that's how clients software outputs CSV and we can't change it. I am looking for solution on how to combine columns after nth column. So for an example, after 6th column I need ti combine all columns in row to 7th.
Is that possible to achieve?
I would paste the code I'm working on but it's sample I've found online using fgetcsv function and outputing table.
Also, is it possible to read rows instead of columns like it renders it?
Anyone who helps out will do HUGE favor!
I have a project going on and this is the first time I've encountered CSV. I've read numerous post but haven't found what I need.
So we have and CSV with values like this
Name,Country,Color,Pet
David,UK,Red,Dog
Andy,USA,Blue,Cat,Dog,Fish
...
So sometimes there are multiple values on "Pet", and that's how clients software outputs CSV and we can't change it. I am looking for solution on how to combine columns after nth column. So for an example, after 6th column I need ti combine all columns in row to 7th.
Is that possible to achieve?
I would paste the code I'm working on but it's sample I've found online using fgetcsv function and outputing table.
Also, is it possible to read rows instead of columns like it renders it?
Anyone who helps out will do HUGE favor!
Share Improve this question edited Jan 23, 2018 at 2:36 majick 5,1412 gold badges18 silver badges30 bronze badges asked Jan 22, 2018 at 22:37 DavidDavid 872 silver badges15 bronze badges2 Answers
Reset to default 0Not too hard really...
$csvdata = file_get_contents($filepath);
$lines = explode("\n", $csvdata); // split data by new lines
foreach ($lines as $i => $line) {
$values = explode(',', $line); // split lines by commas
// set values removing them as we ago
$linevalues[$i]['name'] = trim($values[0]); unset($values[0]);
$linevalues[$i]['country'] = trim($values[1]); unset($values[1]);
$linevalues[$i]['color'] = trim($values[2]); unset($values[2]);
// assign remaining columns (array)
$linevalues[$i]['pet'] = array_values($values);
}
print_r($linevalues); // see the result
You can try to use php-parsecsv
library.
If you deal with multiple values in one cell (eg "Red;Green;Blue
"), separated by some char and you need to convert this cell value to array - take a look at:
https://packagist/packages/decss/item-parser