所以,我得到了这个错误,即使我正在做的代码完成了我想要的工作。我将尝试逐行解释代码。
$bits = array();//bits is the array that I use to hold the array that explodes each line
$explParts = array();
$parts = NULL;//variable that holds the 6 item in array (0 index so later i use parts[5])
$articleCount = 0;//variable that holds the counter for article
foreach ($files as $dataz) { //loop that goes through all files in folder
$handle = fopen('data/'.$dataz, 'r');//open the first file, and second after it finished the first
while (!feof($handle)){//while not end of file {do}
$newLine = fgets($handle);//$newLine holds the *(1,2,3) line;
$bits = explode(" ", $newLine);//$bits hold the array that is created after the explosion of first line
//print_r(array_values($bits));//uncomment this if you want to see what are the values inside bits;
$parts = $bits[5];//$parts is the variables that holds the 6th item in the $bits array
$explParts = explode("/", $parts); //$explParts is the array that holds the items from parts that are exploded
$findArticle = $explParts[0];//$findArticle holds the 1st ideam in $explPart array.
$findArticle = trim($findArticle);//trimmed the value so spaces are deleted.
if ($findArticle == "articles") {//if what's inside $findArticle == "articles", add 1 to the counter
$articleCount++;
}
}
}
echo '<p> The number of requests from the articles directory is: '.$articleCount.'</p>'; //displays the total number of request from the articles directory
fclose($handle);//close $handle
问题是,即使你我得到了正确的文件数量,我在文件中得到了这个错误:
Notice: Undefined offset: 5 in /home/otoma01/public_www/p1tma/trytask2.php on line 38
Call Stack: 0.0011 332600 1. {main}() /home/otoma01/public_www/p1tma/trytask2.php:0
Notice: Undefined offset: 5 in /home/otoma01/public_www/p1tma/trytask2.php on line 38
Call Stack: 0.0011 332600 1. {main}() /home/otoma01/public_www/p1tma/trytask2.php:0
Notice: Undefined offset: 5 in /home/otoma01/public_www/p1tma/trytask2.php on line 38
Call Stack: 0.0011 332600 1. {main}() /home/otoma01/public_www/p1tma/trytask2.php:0
Notice: Undefined offset: 5 in /home/otoma01/public_www/p1tma/trytask2.php on line 38
Call Stack: 0.0011 332600 1. {main}() /home/otoma01/public_www/p1tma/trytask2.php:0
看起来我在$parts=$bits[5]中使用的5有问题。
但这只是我想从数组中提取的部分的索引。
解决方案,每个人都可以通过评论来简化。
$bits = array();
$articleCount = 0;
foreach ($files as $dataz) {
$handle = fopen('data/'.$dataz, 'r');
while (!feof($handle)){
$newLine = fgets($handle);
$bits = explode(" ", $newLine);
if (empty($newLine)) {
continue;
}
$parts = $bits[5];
$explParts = explode("/", $parts);
$findArticle = $explParts[0];
$findArticle = trim($findArticle);
if ($findArticle == "articles") {
$articleCount++;
}
}
}
echo '<p> The number of requests from the articles directory is: '.$articleCount.'</p>';
fclose($handle);