我想在PHP上输出下面看起来像jasondata的jason数据。 folder
是文件夹的名称,title
位于info.txt
的第一行。 info.txt
位于该文件夹下。每个info.txt
中有三行,这些行只是通过创建新行(不是逗号)来分隔。文件夹books
和我的php
文件位于同一文件夹下。我该如何编写PHP代码?谢谢。
我的PHP代码在这里;
function books(){
$array = [];
$story = glob("books/" . "*");
foreach($story as $each){
$title = file($each ."/info/txt", FILE_IGNORE_NEW_LINES);
$output = array (
"title" => $title[0],
"folder" => $each #i would like to put the name of the folder here
);
array_push($array,$review);
}
print(json_encode($array));
}
Json数据应该是这样的;
{
"books" : [
{
"title": "Harry Potter and the Prisoner of Azkaban",
"folder": "harrypotter"
},
{
"title": "The Hobbit",
"folder": "hobbit"
},
... (one entry like this for each folder inside books/)
]
}
答案 0 :(得分:0)
使用DirectoryIterator或scandir函数,请尝试以下代码
$dirs = '/directory/';
$dir = new DirectoryIterator($dirs);
$array = array();
foreach ($dir as $key => $fileinfo) {
if ($fileinfo->isDir()) {
//remove hidden files or dot files
if ( $fileinfo->getBasename() === '.' || $fileinfo->getBasename() === '..' ) continue);
//foldername
$array[$key]['folder'] = $fileinfo->getBasename();
//title
$array[$key]['title'] = file($array[$key]['folder'].'/info.txt' , FILE_IGNORE_NEW_LINES);
}
}
$json = json_encode($array);
print_r($json);
让我知道它是否有效。
<强>编辑强> 我尝试在我的本地主机上工作
$dirs = 'books/';
$dir = new DirectoryIterator($dirs);
$array = array();
foreach ($dir as $key => $fileinfo) {
if ($fileinfo->isDir()) {
//remove hidden files or dot files
if ( $fileinfo->getBasename() === '.' || $fileinfo->getBasename() === '..' ) continue;
//foldername
$array[$key]['folder'] = $fileinfo->getBasename();
//title
$array[$key]['title'] = file($dirs.'/'.$array[$key]['folder'].'/info.txt' , FILE_IGNORE_NEW_LINES);
}
}
$json = json_encode($array);
echo '<pre>'.print_r($json, true).'</pre>';
<强>截图强>