我如何在下面的代码中将目录结果/ pdf的数量限制为8个呢?
$counter = 0;
foreach (glob("/directory/*.pdf") as $path) { //configure path
$docs[filectime($path)] = $path;
}
krsort($docs); // sort by key (timestamp)
foreach ($docs as $timestamp => $path) {
echo '<li><a href="/directory/'.basename($path).'" class="'.($counter%2?"light-grey":"").'" target="_blank">'.basename($path).'</a></li>';
$counter++;
}
这可能很容易,但我似乎无法弄明白 - 提前谢谢,S。
答案 0 :(得分:13)
foreach (array_slice(glob("/directory/*.pdf"),0,8) as $path) {
答案 1 :(得分:1)
检查计数器以及何时从循环中检测到break;
的某个数字。
答案 2 :(得分:0)
Glob没有用于限制结果数量的标志。这意味着您必须检索该目录的所有结果,然后将阵列减少到8个文件路径。
$glob = glob("/directory/*.pdf");
$limit = 8;
$paths = array();
if($glob){ //$glob not false or empty
if(count($glob) > $limit)){ // if number of file paths is more than 8
$paths = array_slice($glob,0,$limit);//get first 8 (alphabetically)
} else {
// we don't need to splice because there are less that 8 results)
$paths = $glob;
}
// or ternary
$paths = (count($glob) > $limit) ? array_slice($glob,0,$limit) : $glob;
}
foreach ($paths as $path){
...
}
深入了解一下这个例子,这可能不是您实际想要的,因为您想要对结果进行排序。
如果可能,您应该使用GLOB FLAGS。虽然没有标志以特定顺序返回文件,但您可以阻止glob按字母顺序返回它们(默认)。 如果您需要按字母顺序排列文件,请始终使用GLOB_NOSORT标记。
如果您确实希望数组限制为8个文件路径,但也按时间戳顺序排列,那么在拼接数组之前必须先对它们进行排序。
$paths = array();
$limit = 8;
$glob = glob("/directory/*.pdf",GLOB_NOSORT); // get all files
if($glob){ // not false or empty
// Sort files by inode change time
usort($glob, function($a, $b){
return filectime($a) - filectime($b);
});
$paths = (count($glob) > $limit) ? array_slice($glob,0,$limit) : $glob;
}
$docs = array_merge($docs, $paths); // As i couldn't see where $docs was set I didn't want to overwrite the variable.
foreach ($docs as $path) {
$basename = basename($path);
echo '<li><a href="/directory/'.$basename.'" " target="_blank">'.$basename.'</a></li>';
}
<style>
li > a:nth-child(even){
color:#fff;
background-color:lightgrey;
}
</style>