在子目录中找到编号最大的文件夹,并提供json


find biggest numbered folder in subdirectories and serve it with json

文件夹结构如下:

-Manga
   -Berserk
      -345
      -346
   -One Piece
      -840
      -841

并希望JSON输出如下:

{"0" => ["name":"Berserk", "last":"346"],
 "1" => ["name":"One Piece, "last":"841"]}

就像标题所说的,我想要JSON输出,给我漫画文件夹中每个系列的名称和属于该系列的最大编号文件夹。

我现在就有这样的东西。

<?php 
$path = dirname(__FILE__) . "/../../manga"; 
$dir = new DirectoryIterator($path); 
$data = array("mangas"=> array()); 
foreach ($dir as $fileinfo) { 
    if (!$fileinfo->isDot() && $fileinfo->getFilename() !== ".DS_Store") { 
        array_push($data["mangas"], $fileinfo->getFilename()); 
    } 
} 
header('Content-Type: application/json; charset=UTF-8'); 
echo json_encode($data); 
?>

编辑:Slim Framework API

 $app->get('/ana', function ($request, $response, $args) {
 $path = "../../manga"; 
 function getAll($path)
 {
 $dirs = [];
 foreach (new DirectoryIterator($path) as $item) {
    if (!$item->isDir() || $item->isDot()) {
        continue;
    }
    if ($max = getMaxInDir($item->getRealPath())) {
        $dirs[] = [
            'name' => $item->getFilename(),
            'last' => $max,
        ];
    }
}
return $dirs;
}
function getMaxInDir($path)
{
$max = 0;
foreach (new DirectoryIterator($path) as $item) {
    $name = $item->getFilename();
    if (!$item->isDir() || $item->isDot() || !is_numeric($name)) {
        continue;
    }
    if ($current = (int)$name > $max) {
        $max = $current;
    };
}
return $max;
}
return $this->response->withJson(getAll($path));
});

http://127.0.0.1/api/public/ana输出

[{"name":"Berserk","last":true},{"name":"One Piece","last":true}]

首先,您想要的输出不是有效的JSON。应该是

[
    {"name":"Berserk","last":346},
    {"name":"One Piece","last":841}
]

现在有一种方法

echo json_encode(getAll($path));
function getAll($path)
{
    $dirs = [];
    foreach (new DirectoryIterator($path) as $item) {
        if (!$item->isDir() || $item->isDot()) {
            continue;
        }
        if ($max = getMaxInDir($item->getRealPath())) {
            $dirs[] = [
                'name' => $item->getFilename(),
                'last' => $max,
            ];
        }
    }
    return $dirs;
}
function getMaxInDir($path)
{
    $max = 0;
    foreach (new DirectoryIterator($path) as $item) {
        $name = $item->getFilename();
        if (!$item->isDir() || $item->isDot() || !is_numeric($name)) {
            continue;
        }
        if (($current = (int)$name) > $max) { // updated line
            $max = $current;
        };
    }
    return $max;
}