2016-12-05 95 views
1

我想创建一个从3目录载入我的所有文件(.PDF)PHP脚本,并创建一个JSON文件。列表文件从PHP - 创建JSON文件

我试试这个

$dir_2016 = "./HCL/2016"; 
$dir_2015 = "./HCL/2015"; 
$dir_2014 = "./HCL/2014"; 

$files_2016 = array(); 
$files_2015 = array(); 
$files_2014 = array(); 

$json_file = array(
    "2016" => $files_2016, 
    "2015" => $files_2015, 
    "2014" => $files_2014 
); 

if(is_dir($dir_2016) and is_dir($dir_2015) and is_dir($dir_2014)) 
{ 
    // 2016 
    if(is_dir($dir_2016)) 
    { 
     if($dh = opendir($dir_2016)) 
     { 
      while(($file = readdir($dh)) != false) 
      { 
       if($file == "." or $file == ".."){ 

       } else { 
        $files_2016[] = $file; // Add the file to the array 
       } 
      } 
     } 
    } 

    // 2015 
    if(is_dir($dir_2015)) 
    { 
     if($dh = opendir($dir_2015)) 
     { 
      while(($file = readdir($dh)) != false) 
      { 
       if($file == "." or $file == ".."){ 

       } else { 
        $files_2015[] = $file; // Add the file to the array 
       } 
      } 
     } 
    } 

    // 2014 
    if(is_dir($dir_2014)) 
    { 
     if($dh = opendir($dir_2014)) 
     { 
      while(($file = readdir($dh)) != false) 
      { 
       if($file == "." or $file == ".."){ 

       } else { 
        $files_2014[] = $file; // Add the file to the array 
       } 
      } 
     } 
    }  
    echo json_encode($json_file); 
} 

但输出是:

{"2016":[],"2015":[],"2014":[]} 

的files_2014 [],files_2015 [],files_2016 []是空的。

什么,我做错了什么?

+2

json_file移动的$您定义的底部。在您分配$ files_2016的位置,该变量为*空*。在插入之前必须先填充它。 –

+2

移动此'$ json_file =阵列( “2016”=> files_2016 $, “2015”=> $ files_2015, “2014”=> $ files_2014 ); '在你的所有循环之后 – nospor

+3

你有没有考虑重构你的代码?这真的是重复的。类似https://3v4l.org/DqJAf也可以。 – Yoshi

回答

0

建立在我的上述评论,这里有一个廉价方式得到的只有PDF格式的文件名,在给定的目录:

<?php 
header('Content-Type: application/json; charset="utf-8"'); 

$dirs = [ 
    './HCL/2016', 
    './HCL/2015', 
    './HCL/2014', 
]; 

$files = []; 

foreach ($dirs as $dir) { 
    if (is_dir($dir)) { 
     $files[basename($dir)] = glob($dir . '/*.pdf'); 
    } 
} 

array_walk_recursive($files, function (&$entry) { 
    $entry = basename($entry); 
}); 

echo json_encode($files, JSON_PRETTY_PRINT); 

注意,还有的如何获得目录中的所有文件等多种方式,所以这绝不是唯一的解决办法。

1

你应该你的$json_file定义移至底部如下:

// ... get files code 
$json_file = array(
    "2016" => $files_2016, 
    "2015" => $files_2015, 
    "2014" => $files_2014, 
); 
echo json_encode($json_file); 

因为arraypassing by value而非passing by reference

而且,一个更好的方式来获取文件和子目录的目录浅是使用scandir,例如:

$files_2014 = array_slice(scandir('./HCL/files_2014'), 2) 

参见:http://php.net/manual/en/function.scandir.php