admin管理员组文章数量:1316841
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
本文标签: Reading CSV values and showing them in PHP
版权声明:本文标题:Reading CSV values and showing them in PHP 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742014611a2413535.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论