I am trying to display the total number in each line of a file that does not contain a path to another file as well as the filename, but if it has a path to another file loop through that file and sum all the number it has and the loop goes on and on as long as there exists a path to a file in the current file.
here is my code
function fileProcessor($value){
if(file_exists(trim($value))){
$total = 0;
$files = file($value, FILE_SKIP_EMPTY_LINES);
foreach($files as $data) {
if(!preg_match("/.txt/i", $data)){
$num = floatval($data);
$total += $num;
} else {
fileProcessor(trim($data));
}
}
echo $value. ' - ' .($total);
} else {
echo 'File does not exist';
}
fileProcessor('text_files/first.txt');
}
I have 3 .txt files I'm working with, inside those files I have something like this
first.txt
- 1
- 3
- 3
- second.txt
second.txt
- 2
- 3
- third.txt
third.txt
- 1
- 2
The output I am looking for
- first.txt - 15
- second.txt - 8
- third.txt - 3
I will really appreciate it if someone can point me in the right direction, I don't know if I'm doing it right.
There are two problems with your code:
Correcting those issues, and renaming the variables to something meaningful gives this code:
Output:
This lists the files in the order in which the totals are finally accumulated, so the lowest levels appear first.
[Edit] I spotted a problem with the order of results if two or more filenames appear in a file. Here's a reworked version that deals with that.
To list the files in the order in which they are encountered requires reversing the natural order. In the new version below I've placed the filenames in a
$fileList
array which is passed down by reference. Each new invocation of the function adds its results to the end of that array. Once processing is complete the array is displayed.Output: