Reputation: 99
I have dynamic multidimensional array like this :
Array
(
[0] => index.php
[src] => Array
(
[src2] => Array
(
[src3] => Array
(
[0] => test_src3.php
)
[0] => Array
(
[0] => test_src2.php
)
)
[0] => test_src.php
)
[src_test] => Array
(
[New Folder] => Array
(
)
[src_test2] => Array
(
[New Folder] => Array
(
)
[src_test3] => Array
(
)
)
)
[1] => test.php
)
The number of dimensions might be change based on sub directories that found in a folder path inputted by user (this program is used by a person in their local).
How could i fetch those array elements so that the result would be like this :
array(
[0] => src/src2/src3
[1] => src_test/New Folder
[2] => src_test/src_test2/New Folder/
[3] => src_test/src_test2/src_test3
)
By the way i have a function to achieve this :
function getKeyPaths(array $tree, $glue = '/'){
$paths = array();
foreach ($tree as $key => &$mixed) {
if (is_array($mixed)) {
$results = getKeyPaths($mixed, $glue);
foreach ($results as $k => &$v) {
$paths[$key . $glue . $k] = $v;
}
unset($results);
} else {
$paths[$key] = $mixed;
}
}
return $paths;
}
the above function does not result like what i expected:
Array
(
[0] => index.php
[src/src2/src3/0] => test_src3.php
[src/src2/0/0] => test_src2.php
[src/0] => test_src.php
)
How do i achieve this ?
Upvotes: 0
Views: 67
Reputation: 1275
One approach :
function getKeyPaths(array $tree, $glue = '/', $return_array = true){
$paths = "";
foreach ($tree as $key => &$mixed) {
$path = $key . $glue;
if (is_array($mixed) && !is_int($key) ) {
$paths .= $path . getKeyPaths( $mixed, $glue, false);
if ($return_array) {
$paths .= "|";
}
}
}
if ($return_array) {
return explode("|", trim($paths, "|"));
}
return $paths;
}
Upvotes: 1