2016-12-05 4 views
1

3つのディレクトリからすべてのmyファイル(.pdf)を読み込み、jsonファイルを作成するPHPスクリプトを作成したいとします。リストファイルphp from - 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 = array( " 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のあなたの定義を移動する必要があります:passing by valueいうよりpassing by referenceある

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

arrayので。

そして、ディレクトリ内のファイルやサブディレクトリを取得するためのより良い方法は浅く例えば、scandirを使用している:

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

参照:上記の私のコメントhttp://php.net/manual/en/function.scandir.php