duanlu8613 2013-11-18 12:54
浏览 29
已采纳

PHP如何迭代目录并合并在该名称的单个文件中以相同字符串结尾的所有文件

Description:

I have a directory that contains a large number of files named as follows:

2013_11_weekly.csv 
2013_10_weekly.csv 
2013_08_weekly.csv 
2013_09_weekly.csv 
2013_11_any_string.csv 
2013_10_any_string.csv

Problem:

How can I iterate over the directory and merge all the files that end with the same string into single files?

The end result would be a directory containing the following files.

weekly.csv 
any_string.csv 
...

Research:

I have the following code snippet that merges all all files.

<?php

$files = glob("*.csv");
$out = fopen("merged_files.csv", "w");
foreach($files as $file){
    fwrite($out, file_get_contents($file));
}
fclose($out);
echo "files merged";

?>

How can I amend my script to achieve the above?

I know I may have to use an array function, a str_ function and possibly a regular expression function.

  • 写回答

5条回答 默认 最新

  • dsdf64562672 2013-11-18 13:06
    关注

    This is very simple, you must just figure out, how to fetch common name from filenames.

    In my example, I split filename on 8th position (2013_11_weekly.csv becomes weekly.csv ):

    $files = glob("*.csv");
    $out = array();
    foreach($files as $file) {
        $name = substr(basename($file), 8);
        if (!isset($out[$name])) {
            $out[$name] = fopen($name, "w");
        }
        fwrite($out[$name], file_get_contents($file));
    }
    foreach ($out as $f) {
        fclose($f);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)