Heim  >  Artikel  >  Backend-Entwicklung  >  关于一个数组的转换

关于一个数组的转换

WBOY
WBOYOriginal
2016-06-06 20:52:17917Durchsuche

$a = array('dir1', 'dir2', 'dir3', 'file1');
$b = array('dir1', 'dir2', 'dir3', 'file2');
//上面的数组怎么变成下面这种
/*
array(
	'dir1'=>array(
		'dir2'=>array(
			'dir3'=>array('file1', 'file2',)
		)
	)
);
*/

求个算法,谢谢!

回复内容:

$a = array('dir1', 'dir2', 'dir3', 'file1');
$b = array('dir1', 'dir2', 'dir3', 'file2');
//上面的数组怎么变成下面这种
/*
array(
	'dir1'=>array(
		'dir2'=>array(
			'dir3'=>array('file1', 'file2',)
		)
	)
);
*/

求个算法,谢谢!

亲~好吧,我自己弄出来了。

$a = array('dir1', 'dir2', 'dir3', 'file1');
function build($tree, $arr) {
	if(count($arr) == 1) {
		return $arr;
	}
	$key = array_shift($arr);
	$tree[$key] = build($tree, $arr);
	return $tree;
}

$tree = array();
print_r(build($tree, $a));
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn