为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
慕神8447489 2023-09-08 21:38:32
这很难用标题来解释,但是......我这里有 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 来做到这一点?
查看完整描述

1 回答

?
牧羊人nacy

TA贡献1862条经验 获得超7个赞

考虑到您的 csv 文件的名称是a.csv,这里是代码


<?php


$newCsv = array();


// Get the file in an array

$csv = array_map('str_getcsv', file('a.csv'));


foreach($csv as $row){

    //Get the first column

    $str = $row[0];

    

    // Split the string

    

    $strParts = explode('#', $str);

    $size =  sizeof($strParts);


    // If it contains #?

    if($size > 1){

        $newFirstRow = "'location' : '". $strParts[$size -1]."'";

    } else{

        $newFirstRow = $row[0];

    }

    


    array_push($newCsv, array($newFirstRow, $row[1], $row[2]));

}



// Open the file in write mode ('w') 

// 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'); 

  

// Loop through file pointer and a line 

foreach ($newCsv as $fields) { 

    fputcsv($fp, $fields); 

  

fclose($fp); 



?>


查看完整回答
反对 回复 2023-09-08
  • 1 回答
  • 0 关注
  • 58 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信