I have a directory of ever-changing CSV files that I wish to read and count the number of times a word appears in a certain "column." I'm using the following code to do it successfully with a single file:
$file = 'Some\Random\Directory\myfile.txt');
$fh = fopen($file, 'rb');
$tag = array();
while($col = fgetcsv($fh)) {
if (isset($tag[$col[2]])) {
$tag[$col[2]]++;
} else {
$tag[$col[2]] = 1;
}
}
fclose($fh);
$foo = ($tag['foo']);
$bar = ($tag['bar']);
echo $foo;
But, I have gotten hung up when attempting to parse the entire directory with this code:
$files = glob('Some\Random\Directory\*.txt');
foreach($files as $file){
$fh = fopen($file, 'rb');
$tag = array();
while($col = fgetcsv($fh)) {
if (isset($tag[$col[2]])) {
$tag[$col[2]]++;
} else {
$tag[$col[2]] = 1;
}
}
fclose($fh);
$foo = ($tag['foo']);
$bar = ($tag['bar']);
$foo_sum = array_sum($foo);
}
echo $foo_sum;
This code results in nothing being shown on the page. If I remove the array_sum() function and place the echo inside the loop, all of the instances of foo are displayed, but as one number per file. What is keeping me from obtaining the sum of all the foos?