douzi4724 2015-03-08 02:26
浏览 190
已采纳

Php重新排序并添加到csv文件

I need to have a script that I can upload a CSV to and have it output the contents in a new order with some fields removed and some added. I have tried getting the csv into an array but emails seem to break it. An input might look like this:

col1, col2, col3, col4
name, addr, phon, emal
...

The output would need to be changed to:

col4, col1, col3, col5
emal, name, addr, stat
...

Notice col3 is gone and col5 is added. col5 is the same value for every row.

I was doing this with a foreach loop. Which worked but its kind of slow. I dont know if there is a better or faster way.

Edit:

The answer seems to work but it raises two other features that will help:

One, I have a field that includes a date and time like 1/31/15 23:59. is there an easy way to strip the last 6 characters?

Two, can we skip a line if say col3 has data? I have a refunded date column that I would like to skip over if theres a date in it. Its blank otherwise. I know I can use isset but I dont know how to make the loop skip and continue if col3 isset. Also I dont know if isset might still be TRUE if theres no data since the column still exists

  • 写回答

1条回答 默认 最新

  • duanli4146 2015-03-08 02:41
    关注
    <?php
        $sInFile  = 'infile.csv';
        $sOutFile = 'outfile.csv';
    
        $iRow = 0;
        if( ( $rHandle = fopen( $sInFile, "r")) !== FALSE ) 
        {
            while( ( $aData = fgetcsv( $rHandle, 1000, ",") ) !== FALSE ) 
            {
                // Skip headers.
                if( $iRow != 0 )
                {
                    $iCountColumns = count( $aData );
                    for( $i = 0; $i < $iCountColumns; ++$i )
                    {
                        // Source
                        // name, addr, phon, emal
                        $sTmp  = '';
                        $sTmp .= $aData[ 3 ];
                        $sTmp .= ', ';
                        $sTmp .= $aData[ 0 ];
                        $sTmp .= ', ';
                        $sTmp .= $aData[ 1 ];
                        $sTmp .= ', ';
                        $sTmp .= 'CONSTANT!'; 
                        $sTmp .= "
    "; 
                        // Output
                        // emal, name, addr, stat
                    }
                    file_put_contents( $sOutFile, $sTmp, FILE_APPEND | LOCK_EX );
                }
                ++$iRow;
            }
        }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分