Home > Article > Backend Development > 求数组重组代码
数组 重组
我现在有一个数组如下:
$arr=array( '0' => Array ( 'size' => 123, 'path' => Array ( '0' => 'a', '1' => 'b', '2' => 'c', '3' => 'abc', ) ), '1' => Array ( 'size' => 456, 'path' => Array ( '0' => 'd', '1' => 'e', '2' => 'f', '3' => 'def', ) ));$ar=array();foreach($arr as $k=>$v){ $ar[$k][$v['path'][0]][$v['path'][1]][$v['path'][2]]['size']=$v['size']; $ar[$k][$v['path'][0]][$v['path'][1]][$v['path'][2]]['name']=$v['path'][3];}print_r($ar);
$arr=array( '0' => Array ( 'size' => 123, 'path' => Array ( '0' => 'a', '1' => 'b', '2' => 'c', '3' => 'abc', ) ), '1' => Array ( 'size' => 456, 'path' => Array ( '0' => 'd', '1' => 'e', '2' => 'f', '3' => 'def', ) ));$ar=array();foreach($arr as $k=>$v){ $ar[$k][$v['path'][0]][$v['path'][1]][$v['path'][2]]['size']=$v['size']; $ar[$k][$v['path'][0]][$v['path'][1]][$v['path'][2]]['name']=$v['path'][3];}print_r($ar);
$ar = array( '0' => Array( 'size' => 123, 'path' => Array( '0' => 'a', '1' => 'b', '2' => 'c', '3' => 'abc', ) ), '1' => Array( 'size' => 456, 'path' => Array( '0' => 'd', '1' => 'e', '2' => 'f', '3' => 'def', ) ));foreach($ar as $item) { $t = array(); $p =& $t; foreach($item['path'] as $i=>$k) { if(strlen($k) > 1) { //注 $item['path'] = $k; $p = $item; break; } $p[$k] = array(); $p =& $p[$k]; unset($item['path'][$i]); } $res[] = $t;}print_r($res);/*注:这个结束条件太牵强,但你又没有给出结束条件,只能观察结果勉强为之不过是个引用的练习罢了*/
Array( [0] => Array ( [a] => Array ( [b] => Array ( [c] => Array ( [size] => 123 [path] => abc ) ) ) ) [1] => Array ( [d] => Array ( [e] => Array ( [f] => Array ( [size] => 456 [path] => def ) ) ) ))
多谢啦,对PHP不是很熟悉