each line of The file $wordFile [which is over hundreds of lines],consists of a word + 'space' + decimal number + ' '.
I need to extract the number and word from the file and add them to the $indivFreq array. But am getting error
Notice: Undefined offset: 1 in /.....
This is my code:
$wordFile = file_get_contents("wordFile.txt");
$termArr = explode("
", $wordFile);
$wordFile2 = file_get_contents("wordFile2.txt");
$termArr2 = explode("
", $wordFile2);
$cityFreqsArr = array($termArr, $termArr2);
$twoTerms = array();
$decimalScore = number_format("0", 8);
$indivFreqs = array("", $decimalScore);
$twoDimFreqArr = [[]];
for($i=0; $i<count($termArr); $i++){
for($i2=0; $i2 < count($cityFreqsArr[$i]); $i2++){
$currentTerm = $cityFreqsArr[$i][$i2];
$currentTerm = trim($cityFreqsArr[$i][$i2]);
$twoTerms = explode(' ', $currentTerm); //separating each string of term and its frequency into the 2 parts
$indivFreqs[0] = $twoTerms[0];
$indivFreqs[1] = $twoTerms[1]; //**error is here
$twoDimFreqArr[$i][$i2] = $indivFreqs; //for each city and each term there is an array with the term and its frequency
//i.e.,
}
}
I tried printing out the contents of $twoTerms after the explode and am getting arrays with index 0 => word and index 1 => number, Which is why I don't understand why php won't see that it has an index of 1 also?
You've defined $cityFreqsArr
as a 2-dimensional array with number of rows equal to files being read(which for this particular example is 2. first row(with $index=0
) is holding $wordFile.txt
/$termArr
's data. And second row for the second one.
Now for storing data for each city, each term & their respective term & frequency you should first traverse $cityFreqsArr
by its rows (as files) & then second level $index
(as content of each file). So, I updated first & second for
's conditions regarding this.
$wordFile = file_get_contents("wordFile.txt");
$termArr = explode("
", $wordFile);
$wordFile2 = file_get_contents("wordFile2.txt");
$termArr2 = explode("
", $wordFile2);
$cityFreqsArr = array($termArr, $termArr2);
$twoTerms = array();
$decimalScore = number_format("0", 8);
$indivFreqs = array("", $decimalScore);
$twoDimFreqArr = [[]];
for ($i = 0; $i < count($cityFreqsArr); $i++) { //Traversing file by file
for ($i2 = 0; $i2 < count($cityFreqsArr[$i]); $i2++) { //Traversing in each file
$twoTerms = explode(' ', trim($cityFreqsArr[$i][$i2]));
$indivFreqs[] = $twoTerms[0];
$indivFreqs[] = $twoTerms[1];
$twoDimFreqArr[$i][$i2] = $indivFreqs;
}
}
// Test it:
echo '<pre>';
print_r($twoDimFreqArr);
echo '</pre>';