sort files to create object of all files

42 views Asked by At

i am trying to get all images from their folders under a directory and make them to an object. folders names are product id's and filenames are just numbers.

i have this code

            $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.' ';
                    }
                }
//      

            }

that makes

 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..

i want something like this, i think..

{files:{767:[ 1.jpg, 2.jpg ],768:[ 1.jpg, 2.jpg ]}}

thank you.

1

There are 1 answers

0
Shahzad Fateh Ali On

Here is the solution

        $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);