[英]Building paths from multidimensional array in PHP
我有一個數組,如:
$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'
)
),
)
);
我正在嘗試構建一個路徑數組:
$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',
...
);
我似乎無法找到實現這一目標的方法。 我遇到的問題是文件夾名稱可以是數組鍵,也可以是數組元素。
這是我到目前為止所做的,但我沒有接近解決方案......
$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;
}
這樣的事怎么樣?
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;
}
你朝着正確的方向前進,但有點錯過了標記。 函數中的遞歸函數調用之前的return語句導致從不調用foreach循環之后的所有內容。
這是另一個解決方案,利用RecursiveArrayIterator和RecursiveIteratorIterator :
function generatePaths( array $tree ) {
$result = array();
$currentPath = array();
$rii = new RecursiveIteratorIterator( new RecursiveArrayIterator( $tree ), RecursiveIteratorIterator::SELF_FIRST );
foreach( $rii as $key => $value ) {
if( ( $currentDepth = $rii->getDepth() ) < count( $currentPath ) ) {
array_splice( $currentPath, $currentDepth );
}
$currentPath[] = is_array( $value ) ? $key : $value;
$result[] = implode( '/', $currentPath );
}
return $result;
}
PS。:Baconics的解決方案似乎是我的解決方案的兩倍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.