-1

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!

2 Answers 2

0

Not 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
3
  • array_shift() would make this much cleaner, I feel. Also, there's an s missing in unset($value[2]);.
    – janh
    Jan 23, 2018 at 8:00
  • @janh cleaner yes but not clearer, just trying to keep code in answers more understandable for any newcomers by being step by step, makes it easier to modify if needs change. fixed the typo tho cheers.
    – majick
    Jan 24, 2018 at 2:00
  • CSV has escaping, you should use the existing PHP APIs to parse it. Jan 24, 2018 at 3:53
0

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.org/packages/decss/item-parser

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.