I have data contained in an array which is like so,
$file['info']['files'] = array(
[0] => array(
'length' => (int),
'path' => array (
[0] => 'file.txt',
),
),
[1] => array(
'length' => (int),
'path' => array (
[0] => 'directory one',
[1] => 'file2.txt',
),
),
[2] => array(
'length' => (int),
'path' => array (
[0] => 'directory one',
[1] => 'directory two',
[2] => 'file3.txt',
),
),
);
The $file['info']['files']
array can contain any number of elements. The path
array contained in each $file['info']['files']
array is where I am having trouble.
It contains information about a file structure. If just 1 element exists then it is a file. If more than one element exists then each element starting from the top is a parent folder of the next element and the last element is the file in the last folder. Taking the example above would be a file structure of
FILE file1.txt
FOLDER directory one
FILE file2.txt
FOLDER directory two
FILE {file3.txt}
I would like to extract this data into my own array structure which is to be as follows,
$sortedFiles = array(
'file1.txt' => (int),
'directory one' => array(
'file2.txt' => (int),
'directory two' => array(
'file3.txt' => (int),
),
),
);
I have this code so far,
foreach($file['info']['files'] as $file) {
// LENGTH AND PATH ARE SET
if(isset($file['length'], $file['path'])) {
// GET COUNT OF FILE PATH ARRAY
$count = count($file['path']);
// SINGLE FILE
if($count == 1) {
$sortedFiles[$file['path'][0]] = $file['length'];
// FILES IN DIRECTORY
} else {
// BUILD ARRAY STRUCTURE FOR DIRECTORIES
}
}
}
I am having trouble when it comes to adding directories to the array. I could do it manually and only go so many directories down each time checking if the array for the directory exists and if not create it, and if it does exist then add to it. I tried this with the code below but it only goes one directory deep (the code went where it says // BUILD ARRAY STRUCTURE
above).
// FOLDER NOT SET
if(!isset($files[$file['path'][0]])) {
$sortedFiles[$file['path'][0]] = array($file['path'][1] => $file['length'],);
// FOLDER SET
} else {
$sortedFiles[$file['path'][0]][$file['path'][1]] = $file['length'];
}
How can I dynamically create arrays for each directory that exists and add the information that is needed bearing in mind that the directory structure could be any amount of levels deep?
Thanks for taking the time to read my rather long question and I appreciate any help that anyone gives to me.