2014-01-25 134 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