ski*_*ato 4 php multidimensional-array
我有一个数组,如:
$tree = array(
'folder_1' => array(
'folder_1_1',
'folder_1_2' => array(
'folder_1_2_1',
'folder_1_2_2'
),
'folder_1_3'
),
'folder_2' => array(
'folder_2_1' => array(
'folder_2_1_1' => array(
'folder_2_1_1_1',
'folder_2_1_1_2'
)
),
)
);
Run Code Online (Sandbox Code Playgroud)
我正在尝试构建一个路径数组:
$paths = array(
'folder_1',
'folder_1/folder_1_1',
'folder_1/folder_1_2',
'folder_1/folder_1_2/folder_1_2_1',
'folder_1/folder_1_2/folder_1_2_2',
'folder_2',
'folder_2/folder_2_1',
...
);
Run Code Online (Sandbox Code Playgroud)
我似乎无法找到实现这一目标的方法.我遇到的问题是文件夹名称可以是数组键,也可以是数组元素.
这是我到目前为止所做的,但我没有接近解决方案......
$paths = transform_tree_to_paths($trees);
function transform_tree_to_paths($trees, $current_path = '', $paths = array())
{
if (is_array($trees)) {
foreach ($trees as $tree => $children) {
$current_path .= $tree . '/';
return transform_tree_to_paths($children, $current_path, $paths);
}
$paths[] = $current_path;
$current_path = '';
} else {
$paths[] = $trees;
}
return $paths;
}
Run Code Online (Sandbox Code Playgroud)
这样的事怎么样?
function gen_path($tree, $parent=null) {
$paths = array();
//add trailing slash to parent if it is not null
if($parent !== null) {
$parent = $parent.'/';
}
//loop through the tree array
foreach($tree as $k => $v) {
if(is_array($v)) {
$currentPath = $parent.$k;
$paths[] = $currentPath;
$paths = array_merge($paths, gen_path($v, $currentPath));
} else {
$paths[] = $parent.$v;
}
}
return $paths;
}
Run Code Online (Sandbox Code Playgroud)
你朝着正确的方向前进,但有点错过了标记.函数中的递归函数调用之前的return语句导致从不调用foreach循环之后的所有内容.