経緯
https://github.com/kamranahmedse/developer-roadmap
元ネタは上記記事から拾った。
実装
ソースコード全体は下記の通り。
<?php
// Scan current dir or specified dir
function scanDirectory($pathname){
if(!is_dir($pathname) || basename($pathname) === "." || basename($pathname) === ".."){
return basename($pathname);
}
$dirs = scandir($pathname);
//var_dump($dirs);
$result = [];
foreach($dirs as $dir){
$scanned_dir = scanDirectory($pathname . "/" . $dir);
if(is_string($scanned_dir)){
$result[$scanned_dir] = null;
}else{
$result[$dir] = $scanned_dir;
}
}
return $result;
}
$json = json_encode(scanDirectory(realpath(".")),JSON_PRETTY_PRINT);
file_put_contents("directories.json",$json);
scanDirectory関数はカレントディレクトリを解析し、引数がディレクトリのときは親子関係を表現した配列を、ファイルのときや「.」、「..」のときはファイル名のみを返す再帰関数である。
そして得られた配列をjson_encode関数でエンコードし、ファイルに書き出す、というシンプルなスクリプトができた。
動かしてみる
下記のディレクトリ構造の場合にスクリプトを動かしてみた。
> find . | sort | sed '1d;s/^\.//;s/\/\([^/]*\)$/|--\1/;s/\/[^/|]*/| /g'
|--_dirtest
| |--_dir00
| | |--_dir10
| | | |--_file20
| | |--_dir11
| |--_dir01
| | |--_dir10
| | |--_dir11
| | | |--_file21
|--dir-json.php
|--directories.json
|--make_test_file.sh
出力されるJSONは下記の通り。
{
".": null,
"..": null,
"_dir00": {
".": null,
"..": null,
"_dir10": {
".": null,
"..": null,
"_file20": null
},
"_dir11": {
".": null,
"..": null
}
},
"_dir01": {
".": null,
"..": null,
"_dir10": {
".": null,
"..": null
},
"_dir11": {
".": null,
"..": null,
"_file21": null
}
},
"dir-json.php": null,
"directories.json": null,
"make_test_file.sh": null
}