0

下面的代码将回显每个文件中的关键字,是否可以让结果(每个文件的关键字)按字母顺序显示。

<?php 
$files = (glob('{beauty,careers,education,entertainment,pets}/*.php', GLOB_BRACE)); 

    $selection = $files;
    $files = array();

    $keywords = $matches[1];

    foreach ($selection as $file) {    
    if (basename($file) == 'index.php') continue;
    if (basename($file) == 'error_log') continue;
    $files[] = $file;    
}
    foreach($files as $file) {
        $title = str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME));

    $content = file_get_contents($file);
    if (!$content) {

        echo "error reading file $file<br>";
    }
    else {
        preg_match("/keywords = \"(.*?)\"/i", $content, $matches);
        $keywords = $matches[1];
    }
        $results .= '<li><a href="http://domain.com/' . htmlentities($file, ENT_QUOTES) . '">'.$keywords.'</a></li>';    
}
?>
<?=$results?>
4

2 回答 2

0

在 $keywords 上使用 sort()。有一些拼写错误和未使用的变量。在所有文件都被处理之前,您不需要构建 $results HTML,因此将 $results = '' 移出处理文件的 foreach 循环,然后排序,然后 foreach 关键字并构建 $results。

<?php 
$selection = (glob('{beauty,careers,education,entertainment,pets}/*.php', GLOB_BRACE)); 

$files = array();

// $keywords = $matches[1];

foreach ($selection as $file) {      
    if (basename($file) == 'index.php') continue;
    if (basename($file) == 'error_log') continue;
    $files[] = $file;      
} 

foreach($files as $file) { 
    //$title = str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME));

    $content = file_get_contents($file);
    if (!$content) { 

        echo "error reading file $file<br>";
    } 
    else { 
        preg_match("/keywords = \"(.*?)\"/i", $content, $matches);
        $keywords[] = $matches[1];
    } 
} 

$results = '';
sort($keywords); //comment this out to see the effects of the sort()
foreach($keywords as $_k) { 
    $results .= '<li><a href="http://domain.com/' . htmlentities($file, ENT_QUOTES) . '">'.$_k.'</a></li>';      
} 
?>
<?=$results?>
于 2013-01-26T16:46:00.900 回答
0

用于sort()对关键字数组进行排序:

$keywords = array();

// ...

$keywords[] = $matches[1];
sort($keywords);
于 2013-01-26T16:35:06.167 回答