php echo按字母顺序排列

时间:2013-01-26 16:33:27

标签: php

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

<?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?>

2 个答案:

答案 0 :(得分:0)

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

$keywords = array();

// ...

$keywords[] = $matches[1];
sort($keywords);

答案 1 :(得分:0)

在$ keywords上使用sort()。有一些拼写错误和未使用的变量。在所有文件都是进程之前,您不需要构建$ results HTML,因此将$ results =''移出处理文件的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?>