我正在尝试从目录下的文件夹中获取所有图像并将它们转换为对象。文件夹名称是产品ID,文件名只是数字。
我有这个代码
$dir = "./public/img/product/";
$scandir = scandir($dir);
$opendir = opendir($dir);
$allfiles = new stdClass();
while (false !== ($dirname = readdir($opendir)))
{
if($dirname != "." && $dirname != "..")
{
$allfiles->$dirname = $dirname;
}
}
foreach($allfiles as $folder)
{
$dir = "./public/img/product/".$folder;
$opendir = opendir($dir);
while (false !== ($filename = readdir($opendir)))
{
if($filename != "." && $filename != "..")
{
echo 'folder: '.$folder . ', filname: '.$filename.' ';
}
}
//
}
使
folder: 767, filname: 1.jpg folder: 767, filname: 2.jpg folder: 767, filname: 3.jpg folder: 768, filname: 1.jpg folder: 768, filname: 2.jpg folder: 769, filname: 1.jpg folder: 769, filname: 2.jpg folder: 769, filname: 3.jpg folder: 769..
我想要这样的东西,我想..
{files:{767:[ 1.jpg, 2.jpg ],768:[ 1.jpg, 2.jpg ]}}
谢谢。
答案 0 :(得分:0)
这是解决方案
$dir = "./public/img/product/";
$scandir = scandir($dir);
$opendir = opendir($dir);
$allfiles = new stdClass();
$files = array();
while (false !== ($dirname = readdir($opendir)))
{
if($dirname != "." && $dirname != "..")
{
$allfiles->$dirname = $dirname;
}
}
foreach($allfiles as $folder)
{
$dir = "./public/img/product/".$folder;
$opendir = opendir($dir);
while (false !== ($filename = readdir($opendir)))
{
if($filename != "." && $filename != "..")
{
$files[$folder][] = $filename;
}
}
}
ksort($files);
foreach($files as $index => $folder){
$files[$index] = sort($folder);
}
echo json_encode($files);