Read txt file and repeat lines based on data in file - Write to array or another file.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Thomas_H
Forum Newbie
Posts: 1
Joined: Fri Sep 03, 2021 9:16 am

Read txt file and repeat lines based on data in file - Write to array or another file.

Post by Thomas_H »

First of all, thank you for your help on this.

I have only worked with PHP occasionally and not very very good at it, so I might just be missing a concept or logic.
If you could point me in the right direction, so I can research functionality further that would be great.

I am trying to write a php script that has two requirements:

1) Read a txt file line by line, and write it to an array or another text file.
To meet this requirement I am currently using file() and a foreach to read file line by line to meet the first requirement.

2) Column one of each line will contain an integer. Based on that integer(x), I want to repeat the line x times in the array or file and then move onto next line.

Is this something that I can accomplish with a php script?

2 line sample file. First line should be repeated 6 times and Line 2 repeated 104.
Script should be able to process hundreds of lines.

6 ItemNum1 12846503015697 432 72
104 ItemNum2 34844923450575 7488 72
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Read txt file and repeat lines based on data in file - Write to array or another file.

Post by Celauran »

The data appears to be essentially in CSV format, only the delimiters are not commas. You could use fgetcsv() to read the file and parse each line as an array. Alternately, as you are already reading each line as an array, you could use explode() to convert the line to an array, select the first column (index 0) to get the number of times to repeat, then write the line that number of times to another array for writing later.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Read txt file and repeat lines based on data in file - Write to array or another file.

Post by Christopher »

You have an input array and an output array that will have the replicated lines. You could loop through the array returned by file(), explode each line, find the integer in column one, and append N lines to the output array:

Code: Select all

$input = file('/path/to/my/file.csv');
$output = [];
foreach ($input as $line) {
    $values = explode("\t", $line);
    for ($i=0; $i<$values[0]; ++$i) {
        $output[] = $line;
    }
}
echo "<pre>" . print_r($output, 1) . "</pre>";
This code has not error checking to verify there are lines in the file, column 0 is a positive integer, etc.
(#10850)
Post Reply