2016-01-09 23 views
0

我有一個代碼來搜索目錄中的文件。我使用代碼var_dump($search->foundFiles)在網頁上顯示結果,但我無法弄清楚如何找到正確的代碼以便正確顯示,結果是URL。我怎樣樣式通過var_dump導致數組的顯示

var_dump($search->foundFiles)結果是:

陣列([0] => archivednews/2016年1月8日22:30寨卡病毒存檔news.html [1] => archivednews/2016年1月7日22:30茲卡病毒存檔news.html)

但我想有它顯示在可點擊的鏈接找到的文件像這樣的列表:

<ul> 
    <li><a href="archivednews/2016-01-05 22h30 Zika Virus archived news.html">2016-01-05 22h30 Zika Virus archived news.html</a></li> 
    <li><a href="archivednews/2016-01-04 22h30 Zika Virus archived news.html">2016-01-04 22h30 Zika Virus archived news.html</a></li> 
    <li><a href="archivednews/2016-01-08 22h30 Zika Virus archived news.html">2016-01-08 22h30 Zika Virus archived news.html</a></li> 
</ul> 

這是完整的代碼:

class searchFileContents{ 
    var $dir_name = '';//The directory to search 
    var $search_phrase = '';//The phrase to search in the file contents 
    var $allowed_file_types = array('php','phps');//The file types that are searched 
    var $foundFiles;//Files that contain the search phrase will be stored here 
    var $myfiles; 

    function search($directory, $search_phrase){ 
    $this->dir_name = $directory; 
    $this->search_phrase = $search_phrase; 

    $this->myfiles = $this->GetDirContents($this->dir_name); 
    $this->foundFiles = array(); 

    if (empty($this->search_phrase)) die('Empty search phrase'); 
    if (empty($this->dir_name)) die('You must select a directory to search'); 

    foreach ($this->myfiles as $f){ 
     if (in_array(array_pop(explode ('.', $f)), $this->allowed_file_types)){ 
      $contents = file_get_contents($f); 
      if (strpos($contents, $this->search_phrase) !== false) 
       $this->foundFiles [] = $f; 
     } 
    } 
    return $this->foundFiles; 
    } 

    function GetDirContents($dir){ 
    if (!is_dir($dir)){die ("Function GetDirContents: Problem reading : $dir!");} 
    if ([email protected]($dir)){ 
     while ($file=readdir($root)){ 
      if($file=="." || $file==".."){continue;} 
      if(is_dir($dir."/".$file)){ 
       $files=array_merge($files,$this->GetDirContents($dir."/".$file)); 
      }else{ 
      $files[]=$dir."/".$file; 
      } 
     } 
    } 
    return $files; 
    } 
} 

//Example : 

$search = new searchFileContents; 
$search->search('E:/htdocs/AccessClass', 'class'); 
var_dump($search->foundFiles); 
+1

'var_dump'具有固定的格式。做「foreach」和「echo」值。 –

回答

1

var_dump僅在開發時使用。它只是調試的幫手。 應用程序完成後,您無法將其輸出給用戶。

你可以做到這一點,打印陣列的每個值只作爲後續代碼var_dump會做:

foreach($search->foundFiles as $ffiles) 
    echo "<a href='$ffiles'>$ffiles</a><br>"; 

這將顯示此:

2016-01-05 22h30 Zika Virus archived news.html

2016-01-04 22h30 Zika Virus archived news.html

2016-01-08 22h30 Zika Virus archived news.html

但是陣列中的網址並不是真正的鏈接,所以你必須解決它。

+0

非常感謝,它的作品!但是我怎樣才能排序結果列表,因爲看起來所有的文件都是以隨機順序顯示的? – Rik

+0

它們的順序與var_dump中的順序相同。例如,您可以使用許多數組函數按字母順序排序它們。 – Phiter

+0

謝謝,但我不知道如何排序 – Rik