我想创建一个从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 []是空的。
什么,我做错了什么?
json_file移动的$您定义的底部。在您分配$ files_2016的位置,该变量为*空*。在插入之前必须先填充它。 –
移动此'$ json_file =阵列( “2016”=> files_2016 $, “2015”=> $ files_2015, “2014”=> $ files_2014 ); '在你的所有循环之后 – nospor
你有没有考虑重构你的代码?这真的是重复的。类似https://3v4l.org/DqJAf也可以。 – Yoshi