2016-12-05 30 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