2012-05-05 54 views
1

我在php中編寫了以下對象。它正在工作,但在更改結構中的某些內容後,目錄搜尋器只會將最後找到的目錄保存在數組中。通過掃描目錄丟失對象中的東西

<?php 

include_once('root.php'); 

class crawler 
{ 

private $pages = array(); 

/** 
* @param string $dir 
* @return array current_dir 
*/ 
function found_dir($dir) 
{ 
//   echo "Found (dir): {$dir}\n"; 
    // add $dir to $pages 
    $parts = explode("/", $dir); 
    $current = &$this->pages; 
    // e.g. ./content/page/sub_page/ 
    // [0] => '.' 
    // [1] => 'content' 
    // [-1] => '' 
    for ($i = 2; $i < count($parts) - 1; $i++) { 
     if (!in_array('sub', $current)) 
      $current['sub'] = array(); 
     if (!in_array($parts[$i], $current['sub'])) 
      $current['sub'][$parts[$i]] = array('name' => $parts[$i]); 
     $current = &$current['sub'][$parts[$i]]; 
    } 
    return $current; 
} 

/** 
* @param string $file 
*/ 
function found_file($file) 
{ 
//  echo "Found (file): {$file}\n"; 
    // move to current $dir 
    $current = &$this->found_dir($file); 
    // add $file to $pages 
    $parts = explode(".", substr($file, strrpos($file, "/") + 1)); 
    if (count($parts) == 1) { 
     $current[$parts[0]] = file_get_contents($file); 
    } else { 
     if (strlen($parts[0]) == 0) 
      $current[$parts[1]] = true; 
     else if (!in_array($parts[0], $current)) 
      $current[$parts[0]] = array($parts[1] => file_get_contents($file)); 
     else 
      $current[$parts[0]][$parts[1]] = file_get_contents($file); 
    } 
} 

/** 
* @param string $root 
*/ 
function read_all_files($root = '.') 
{ 
    // vars for handling 
    $directories = array(); 
    $last_letter = $root[strlen($root) - 1]; 
    $root = ($last_letter == '\\' || $last_letter == '/') ? $root : $root . DIRECTORY_SEPARATOR; 
    $directories[] = $root; 

    while (sizeof($directories)) { 
     $dir = array_pop($directories); 
     if ($handle = opendir($dir)) { 
      while (false !== ($file = readdir($handle))) { 
       if ($file == '.' || $file == '..') { 
        continue; 
       } 
       $file = $dir . $file; 
       if (is_dir($file)) { 
        $directory_path = $file . DIRECTORY_SEPARATOR; 
        array_push($directories, $directory_path); 

       } elseif (is_file($file)) 
        $this->found_file($file); 
      } 
      closedir($handle); 
     } 
    } 
} 

/** 
* @return root 
*/ 
public function generatePages() 
{ 
    // get available files, create temp array 
    $this->read_all_files('./content/'); 
    // print 
    print_r($this->pages); 
    // loop array 
    return new root($this->pages); 
} 

} 

我找不到錯誤。也許你們中有人看到了這個錯誤。非常感謝你的幫助!

貝斯特問候

回答

0

您使用in_array,你應該使用isset()函數:

$pages = array('sub' => array()) 

in_array('sub', $pages) => false 
isset($pages['sub']) => true 
+0

非常感謝你。 :) – raubti3r