求数组重组代码
我现在有一个数组如下:
[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
)
)
想重组成如下数组样式,请问怎么写代码啊?
[0] => Array
(
[a] => Array(
[b] => Array(
[c] => Array(
[size] => '123',
[name] => 'abc'
)
)
)
)
[1] => Array
(
[d] => Array(
[e] => Array(
[f] => Array(
[size] => '456',
[name] => 'def'
)
)
)
) 数组 重组
[解决办法]
$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
)
)
)
)
)