I want to convert my directory structure to an array format with file URLs. Here is my directory structure.
public
|-product_001
|-documents
| |- doc_001.txt
| |- doc_002.txt
| |- doc_003.txt
|
|-gallery
|- img_001.png
|- img_002.png
|- img_003.png
And this is what I want:
array(
'product_001' =>array(
'documents' =>array(
0 => "public/product_001/documents/doc_001.txt",
1 => "public/product_001/documents/doc_002.txt",
2 => "public/product_001/documents/doc_003.txt"
)
'gallery' =>array(
0 => "public/product_001/gallery/img_001.png",
1 => "public/product_001/gallery/img_002.png",
2 => "public/product_001/gallery/img_003.png"
)
)
)
Here is the function:
function dirToArray($dir,$url) {
$result = array();
$cdir = scandir($dir);
foreach ($cdir as $key => $value) {
if (!in_array($value, array(".", ".."))) {
if (is_dir($dir . DIRECTORY_SEPARATOR . $value)) {
$url.=DIRECTORY_SEPARATOR.$value;
$result[$value] = dirToArray($dir . DIRECTORY_SEPARATOR . $value,$url);
} else {
$result[] = $url.DIRECTORY_SEPARATOR.$value;
}
}
}
return $result;
}
Here is the conclusion I have received so far:
Array
(
[product_001] => Array
(
[documents] => Array
(
[0] => public/product_001/documents/doc_001.txt
[1] => public/product_001/documents/doc_002.txt
[2] => public/product_001/documents/doc_003.txt
)
[gallery] => Array
(
[0] => public/product_001/documents/gallery/img_001.png
[1] => public/product_001/documents/gallery/img_002.png
[2] => public/product_001/documents/gallery/img_003.png
)
)
)
Can someone help me achieve this? Thank you very much in advance.
source
share