Heim  >  Fragen und Antworten  >  Hauptteil

php - 关于一个数组的转换

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

求个算法,谢谢!

PHP中文网PHP中文网2748 Tage vor387

Antworte allen(1)Ich werde antworten

  • 大家讲道理

    大家讲道理2017-04-10 13:12:21

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

    $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));

    Antwort
    0
  • StornierenAntwort