I have an array like this:
In this array I have folders (dir1, dir2, dir3, etc...) and files. I need to list all the directories and files but printing which is the parent of each element, example: dir2 is child of dir1, dir4 is child of dir2, etc...
The problem is that my recursive function can't iterate over "dir2" because it only obtains "dir3" as directory, directories "dir4", "dir5", "dir7" are missing.
Im breaking my head but I don't get it to work...
This is my code:
<?php
$files = array();
array_push($files, array('root/dir1/dir2/dir3/file1.mkv', "Archivo de vídeo"));
array_push($files, array('root/test.png', "Archivo de imagen"));
array_push($files, array('root/dir1/dir2/dir4/file2.mkv', "Archivo de vídeo2"));
array_push($files, array('root/dir1/dir2/dir4/dir5/file3.mkv', "Archivo de vídeo3"));
array_push($files, array('root/dir1/dir2/dir4/dir5/dir7/file4.mkv', "Archivo de vídeo4"));
$filearray=[];
function scanpath($patharray, $filesize) {
$tree=[];
if(count($patharray)===1) {
$filename=array_pop($patharray);
$tree[] = ['nombre'=>$filename, 'descripcion'=>$filesize];
} else {
$pathpart = array_pop($patharray);
$tree[$pathpart] = scanpath($patharray,$filesize);
}
return $tree;
}
foreach($files as $fileentry) {
$patharray = array_reverse(explode('/',$fileentry[0]));
$thisarray = scanpath($patharray,$fileentry[1]);
$filearray = array_merge_recursive($filearray,$thisarray);
}
echo '<pre>';
print_r($filearray);
echo '</pre>';
function test($arr, $ultimoDirectorio = "") {
foreach($arr as $key => $value) {
if (is_array($value)) {
// Directory
if ($key != "" && !is_numeric($key)) {
$ultimoDirectorio = $key;
}
if (!is_numeric(key($value)) && !is_numeric($key)) {
echo("Directory ".key($value)." inside ".$key."<br>");
}
test($value, $ultimoDirectorio);
} else {
// File
$nombreFichero = $arr['nombre'];
$descripcionFichero = $arr['descripcion'];
echo("Inside: ".$ultimoDirectorio." => File: ".$nombreFichero." - Description: ".$descripcionFichero."<br>");
break;
}
}
}
echo(test($filearray, ""));
The function that iterates is called "test".
Thank's you... this is giving me a serious headache.
question from:
https://stackoverflow.com/questions/65894371/php-recursive-loop-a-file-tree-array-cant-get-all-keys 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…