2014-01-25 53 views
-3

我有問題,按照下面的結構,使陣列目錄(文件夾和文件)到JSON的轉換:將樹形格式的數組轉換爲json。 (PHP)

here

我努力嘗試和網絡,但沒有工作搜索。 最後一個代碼我寫這個任務是:

<?php 
$path = 'data'; 
function get_Dir($path){ 
$dir = scandir($path); 
$filesss = array(); 

$a = 0; 
foreach($dir as $v){ 
    if($v == '.' || $v == '..') continue; 

    if(!is_dir($path.'/'.$v)){ 
     $files[] = 'name:'.basename($v).','.'size:3938'; 
    }else{ 
     $files['name'] = basename($path.'/'.$v); 
     //$change = basename($path.'/'.$v); 
     $files['children'.$a] = get_dir($path.'/'.$v); 

    } 
    $a++; 
} 

return $files; 
} 
?> 

請幫助。 謝謝。

+0

這是什麼有JSON呢?你只是建立一個PHP數組。你是否試圖將結果輸出爲JSON?這是使用'json_encode'的簡單例子... – meagar

+0

我試過了,但無濟於事。 你能幫我編碼嗎? – user3231235

回答

0

試試這個:

<?php 

function getTree($path) { 

    $dir = scandir($path); 

    $items = array(); 

    foreach($dir as $v) { 

     // Ignore the current directory and it's parent 
     if($v == '.' || $v == '..') 
      continue; 

     $item = array(); 

     // If FILE 
     if(!is_dir($path.'/'.$v)) { 

      $fileName = basename($v); 
      $file = array(); 
      $file['name'] = $fileName; 
      $file['size'] = '122'; 

      $item = $file; 

     } else { 
     // If FOLDER, then go inside and repeat the loop 

      $folder = array(); 
      $folder['name'] = basename($v); 
      $childs = getTree($path.'/'.$v); 
      $folder['children'] = $childs; 

      $item = $folder; 

     } 

     $items[] = $item; 

    } 

    return $items; 
} 


$path = 'data'; 
$tree['name'] = 'Main node'; 
$tree['children'] = getTree($path); 

$json = json_encode($tree, JSON_PRETTY_PRINT); 


echo '<pre>'; 
echo $json; 
echo '</pre>'; 

?> 
+0

這是工作謝謝你。 – user3231235