PHP多维数组到平面文件夹视图
发布时间:2020-12-13 17:44:02 所属栏目:PHP教程 来源:网络整理
导读:我有一个像 PHP这样的多维数组: Array( [folder1] = Array ( [folder11] = Array ( [0] = index.html [1] = tester.html ) [folder12] = Array ( [folder21] = Array ( [0] = astonmartindbs.jpg ) ) )) 并应转换为像这样的“文件路径”字符串: Array( [0]
我有一个像
PHP这样的多维数组:
Array ( [folder1] => Array ( [folder11] => Array ( [0] => index.html [1] => tester.html ) [folder12] => Array ( [folder21] => Array ( [0] => astonmartindbs.jpg ) ) ) ) 并应转换为像这样的“文件路径”字符串: Array ( [0] => 'folder1/folder11/index.html' [1] => 'folder1/folder11/tester.html' [2] => 'folder1/folder12/folder21/astonmartindbs.jpg' ) 有什么想法吗? 我已经尝试了很多全部删除…这是我上次尝试的起点: public function processArray( $_array ) { foreach( $_array AS $key => $value ) { if( is_int( $key ) ) { } else { if( is_array( $value ) ) { $this->processArray( $value ); } else { } } } echo $this->string; } 但我没有走到尽头……希望有人可以帮忙吗? 解决方法
递归函数可能是您要搜索的内容.以下功能将起作用:
/** * Flattens the array from the question * * @param array $a Array or sub array of directory tree * @param string $prefix Path prefix of $a */ function flatten($a,$prefix = './') { $paths = array(); foreach($a as $index => $item) { // if item is a string then it is a file name (or a leaf in tree) // prefix it and add it to paths if(is_string($item)) { $paths []= $prefix . $item; } else { // if item is a directory we call flatten on it again. // also we append the new folder name to $prefix foreach(flatten($item,$prefix . $index . '/') as $path) { $paths []= $path; } } } return $paths; } var_dump(flatten($a)); 请注意,flatten()在foreach循环内调用自身,子数组作为参数.这称为“递归算法”. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |