从php列出文件-创建json文件
我想创建一个php脚本,从3目录加载我的所有文件(.pdf),并创建一个json文件 我试试这个从php列出文件-创建json文件,php,json,Php,Json,我想创建一个php脚本,从3目录加载我的所有文件(.pdf),并创建一个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,
$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":[]}
文件_2014[]、文件_2015[]、文件_2016[]为空
我做错了什么 您应该将
$json_文件的定义移动到底部,如下所示:
// ... get files code
$json_file = array(
"2016" => $files_2016,
"2015" => $files_2015,
"2014" => $files_2014,
);
echo json_encode($json_file);
因为数组
是按值传递
而不是按引用传递
另外,一种更好的方法是使用scandir
,例如:
$files_2014 = array_slice(scandir('./HCL/files_2014'), 2)
请参阅:基于我上面的评论,这里有一种只获取给定目录中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);
将$json_文件的定义移到底部。在分配$files_2016时,该变量为空。您必须在插入之前填充它。移动此$json\u file=array(“2016”=>$files\u 2016,“2015”=>$files\u 2015,“2014”=>$files\u 2014)代码>在所有的循环之后,您考虑过重构代码吗?这真是重复。类似的东西也可以。我认为这算是一个输入错误,应该作为such@RiggsFolly或者这是对数组在php中如何工作的误解。例如,“2016”=>&$files\u 2016,
将起作用,尽管这对初学者来说并不明显。