我正在尝试创建一个包含(通过require_once)多个文件的脚本,但我期待以下行为:
仔细观察我原来的剧本后,我发现为什么它没有用。第二个IF语句($ countMissing == 0)在FOR循环中,它为找到的文件生成空数组。将IF语句排除在循环之外就可以解决问题了。
工作版(只需很少的修改):
// Array with required file names
$files = array('some_file', 'other_file', 'another_file');
// Count how many files is in the array
$count = count($files);
// Eampty array for catching missing files
$missingFiles = array();
for ($i=0; $i < $count; $i++) {
// If filename is in the array and file exist in directory...
if (in_array($files[$i], $files) && file_exists(LIBRARIES . $files[$i] . '.php')) {
// ...update array value with full path to file
$files[$i] = LIBRARIES . $files[$i] . '.php';
} else {
// Add missing file(s) to array
$missingFiles[] = LIBRARIES . $files[$i] . '.php';
}
}
// Count errors
$countMissing = count($missingFiles);
// If there was no missing files...
if ($countMissing == 0) {
foreach ($files as $file) {
// ...include all files
require_once ($file);
}
} else {
// ...otherwise show error message with names of missing files
echo "File(s): " . implode(", ", $missingFiles) . " wasn't found.";
}
如果这个帖子没有被删除,我希望它能帮到某个人。
答案 0 :(得分:0)
试试这个,防止循环内循环。
for ($i=0; $i < $count; $i++) {
// If filename is in the array but file not exist in directory...
if (in_array($files[$i], $files) && !file_exists(ROOT_DIR . $files[$i] . '.php')) {
// ...add name of missing file to error array
$errors[] = $files[$i];
}
else{
require_once (ROOT_DIR . $file[$i] . '.php');
}
}
答案 1 :(得分:0)
试试这个:
$files = array(
'some_file',
'other_file',
'another_file',
);
// create full paths
$files = array_map(function ($file) {
return ROOT_DIR . $file . '.php')
}, $files);
// find missing files
$missing = array_filter($files, function ($file) {
return !file_exists($file);
});
if (0 === count($missing)) {
array_walk($files, function ($file) {
require_once $file;
});
} else {
array_walk($missing, function ($file) {
echo "File: " . $file " wasn't found.";
});
}
供参考,见:
答案 2 :(得分:-1)
localheinz和jp的代码可能没问题,但我不会编写类似的东西,因为它会使事情变得复杂。假设你不想要一个丢失文件的列表(这会略有不同),我会这样做:
$filesOK=true;
foreach($files as $file)
{
$path = ROOT_DIR . $file . ".php";
if(!file_exists($path ))
{
$filesOK=false; // we have a MIA
break; // quit the loop, one failure is enough
}
}
if($filesOK)
foreach($files as $file)
require_once($file);
else
echo "We have a problem";
对我来说,这一目了然更容易看到。更容易调试,CPU将以单向或另一方式执行相同的工作。执行速度可能差别不大 - 如果这一点很重要的话。
如果您需要缺失文件列表,则:
$filesOK=true;
foreach($files as $file)
{
$path = ROOT_DIR . $file . ".php";
if(!file_exists($path)) // assume each file is given with proper path
{
$filesOK=false; // we have a MIA
$mia[]=$path; // or $file if you just want the name
}
}
if($filesOK)
foreach($files as $file)
require_once($file);
else
{
if(is_array(@$mia)) // I always make sure foreach is protected
foreach($mia as $badfile) // even if it seems obvious that its ok
echo "Missing in action: $badfile<br>";
}