• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 335
  • Last Modified:

merge files

Hi experts,

I need to merge 2 or more files. No matter the content the script should output lines from 2 or more files into one file.txt, randomized.

Thanks.
0
gloriaewold41
Asked:
gloriaewold41
  • 2
  • 2
1 Solution
 
lwadwellCommented:
To merge known files ... this script will merge them into one, just place the file names into the $files array.  It does not randomize the contents however ... is that important?
<?php
error_reporting(E_ALL);
echo '<pre>';

// old files to be merged
$files   = array('/Apps/DATA/old_file_1.txt', '/Apps/DATA/old_file_2.txt');

// new file name
$newfile = '/Apps/DATA/new_file.txt';
// delete file if already exists
unlink($newfile);

foreach ( $files as $f ) {
    // Open the file to get existing content
    $data = file_get_contents($f);
    
    // Append the contents back to the new file
    file_put_contents($newfile, $data, FILE_APPEND);    
}
echo "done";
?>

Open in new window

0
 
Chris StanyonCommented:
Have a look at this, and ask if you get any probs..

<?php
//read each file into an array.
$file1 = file('input1.txt');
$file2 = file('input2.txt');

//merge the two into one array
$allFiles = array_merge($file1, $file2);

//shuffle (randomize) the array
shuffle($allFiles);

//create or open the file to write to
$output = fopen("output.txt", 'w') or die("can't open file");

//loop through the lines and write them to an output file
foreach ($allFiles as $line) {
	fwrite($output, $line);
}

//close the file
fclose($output);
?>

Open in new window

0
 
gloriaewold41Author Commented:
I need output data randomized.
0
 
Chris StanyonCommented:
My code randomizes the output - it shuffles (randomizes) the lines before writing them to the output file!
0
 
gloriaewold41Author Commented:
Works great. Thanks
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now