2010-06-30 39 views
0

我寫了一個函數來獲取文件夾的所有子文件夾。它也可以選擇上一級並顯示文件夾....非常像文件管理器,但它僅適用於文件夾,並且限制不會超過基本文件夾,以防止用戶瀏覽整個文件夾硬盤。排序顯示文件夾內容的文件夾名稱數組

我將返回結果作爲json對象放在div中。我的問題是這樣的: 在我的窗口框(使用wamp)文件夾「上一級」始終顯示在文件夾列表頂部。當我在我的網站上上傳時,它不會顯示在頂部,而是顯示在中間的某處。我寫了一個函數(fixArray($ array))來糾正這個......但它似乎不起作用。提供了此功能的整個解決方案,因此請幫助使其工作,並使其他人從中受益。 只需要提一下:JS代碼中沒有任何錯誤。 JSON對象按照php文件發送的順序進行解析。

function fixPath($path) { 
    $path = str_replace('/../', '/', $path); 
    $path = str_replace('/./', '/', $path); 
    return $path; 
} 
function fixArray($array) { 
    for($i = 0; $i < count($array); $i++) { 
     if(!strcmp($array[$i]['name'],"Up one Level")) { 
      $aux = $array[$i]; 
      $array[$i] = $array[0]; 
      $array[0] = $array[$i]; 
      break; 
     } 
    } 
} 

function directoryList($basepath, $path) { 
     $dirStruct = array(); 
     if(is_dir($path)) { 
      $handle = opendir($path); 
      while(($file = readdir($handle)) !== false) { 
       if($file != '.') { 
        if(@opendir($path.$file)) { 
         $newpath = ""; 
         if($file == '..') {//begin constructing the path for the upper level 
          $array = @split('/',$path); 

          $up = ""; 
          for($i = 0; $i < count($array) - 2; $i++) { 
           $up = $up.$array[$i].'/'; 
          } 
          $file = "Up one Level"; 
          //if the upper level exceeds the home dir 
          if(strcmp($up,$basepath) < 0) { 
           $newpath = $basepath;//use the basepath 
          } 
          else { 
           $newpath = $up; 
          } 
         } 
         else {//construct the path for a normal dir 
          $newpath = $path.$file.'/'; 
          $newpath = fixPath($newpath); 
         } 
         $dirStruct[] = array('path' => $newpath, 'name'=>$file); 
        } 
       } 
      } 
     } 
     //sortArray($dirStruct); 
     fixpath($dirStruct); 
     return $dirStruct; 
    } 

回答

0

你需要按引用傳遞它保持了更換:)

function fixArray(&$array) { 
    for($i = 0; $i < count($array); $i++) { 
     if($array[$i]['name'] == "Up one Level") { 
      $up = $array[$i]; 
      unset($array[$i]); 
      array_unshift($array,$up); 
      break; 
     } 
    } 
} 
+0

仍然沒有工作。 – user253530 2010-06-30 22:44:14

+0

給它一個去吧現在 – nathan 2010-06-30 23:22:05

0

你交換的交換,然後交換回來。 $array[0] = $array[$i];應該是$array[0] = $aux;

但是,這將交換原始的第一個元素到數組中間。只需將目標元素移動到數組的前面即可。

試試這個:

function fixArray($array) { 
    for($i = 0; $i < count($array); $i++) { 
        if($array[$i]['name'] === "Up one Level") { 
            $aux = $array[$i]; 
            array_unshift($array, $aux); 
            unset($array[$i]); 
            break; 
        } 
    } 
    return $array; 
} 

,並呼籲像:

$dirStruct = fixpath($dirStruct); 
+0

將無法​​正常工作,不通過引用或返回新的數組 - 本質上它只是運行,然後所有的修改都被遺忘;) – nathan 2010-06-30 22:43:55

+0

仍然無法正常工作。 – user253530 2010-06-30 22:52:22

相關問題