Home >Backend Development >PHP Tutorial >一维数组 转 多维数组问题,乱了!
$arr = array('a','b','c','d');
转为
$brr = array(
<code>'a'=>array( 'b'=>array( 'c'=>array( 'd'=>array() ) ) )</code>
);
$arr = array('a','b','c','d');
转为
$brr = array(
<code>'a'=>array( 'b'=>array( 'c'=>array( 'd'=>array() ) ) )</code>
);
<code><?php $arr = ['a', 'b', 'c', 'd']; $child = array(); $res = []; while($v = array_pop($arr)) { $res = [$v => $child]; $child = $res; } print_r($res);</code>
结果为
<code>Array ( [a] => Array ( [b] => Array ( [c] => Array ( [d] => Array ( ) ) ) ) )</code>
看到结构想到了递归,具体代码如下:
<code> function toMany ($arr) { $res = array(); burnArr($res, $arr); return $res; } function burnArr (&$arr, $keys) { if ( !empty($keys) ) { $val = array_shift($keys); $arr[$val] = array(); burnArr($arr[$val], $keys); } else { return ; } } </code>