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条)

报告相同问题?

悬赏问题

  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测