在 PHP 中按分隔符过滤 CSV 文件中的行

这很难用标题来解释,但是......


我这里有 example.csv:


'location': 'United States#Arizona#Mesa', 'value: 10', 'value2: 20'

'location': 'United States#New York', 'value: 24', 'value2: 29'

'location': 'United States#Arizona', 'value: 21', 'value2: 24'

'location': 'United States', 'value: 11', 'value2: 22'

我希望它被重写为:


'location': 'Mesa', 'value: 10', 'value2: 20'

'location': 'New York', 'value: 24', 'value2: 29'

'location': 'Arizona', 'value: 21', 'value2: 24'

'location': 'United States', 'value: 11', 'value2: 22'

通过获取第一行中的所有值,使用“#”分隔符分割它们,然后获取第一个和最后一个值并删除其余的值。我如何使用 PHP 来做到这一点?


慕神8447489
浏览 84回答 1
1回答

牧羊人nacy

考虑到您的 csv 文件的名称是a.csv,这里是代码<?php$newCsv = array();// Get the file in an array$csv = array_map('str_getcsv', file('a.csv'));foreach($csv as $row){&nbsp; &nbsp; //Get the first column&nbsp; &nbsp; $str = $row[0];&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; // Split the string&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; $strParts = explode('#', $str);&nbsp; &nbsp; $size =&nbsp; sizeof($strParts);&nbsp; &nbsp; // If it contains #?&nbsp; &nbsp; if($size > 1){&nbsp; &nbsp; &nbsp; &nbsp; $newFirstRow = "'location' : '". $strParts[$size -1]."'";&nbsp; &nbsp; } else{&nbsp; &nbsp; &nbsp; &nbsp; $newFirstRow = $row[0];&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; array_push($newCsv, array($newFirstRow, $row[1], $row[2]));}// Open the file in write mode ('w')&nbsp;// Remember, this will rewrite the file completely// If you want to backup the file// do it before executing this code$fp = fopen('a.csv', 'w');&nbsp;&nbsp;&nbsp;// Loop through file pointer and a line&nbsp;foreach ($newCsv as $fields) {&nbsp;&nbsp; &nbsp; fputcsv($fp, $fields);&nbsp;}&nbsp;&nbsp;&nbsp;fclose($fp);&nbsp;?>
打开App,查看更多内容
随时随地看视频慕课网APP