日期:2014-05-16 浏览次数:20469 次
header('Content-type: text/html; charset=utf-8');
//以下是原始数组
$array = array(
0=>array(
0=>array(
'text' => '体育',
'children' => array(
0=>array(
'text' => '篮球',
'grade' => '1'
),
1=>array(
'text' => '足球',
'grade' => '3'
)
)
),
1=>array(
'text' => '音乐',
'children' => array(
0=>array(
'text' => '唱歌',
'children' => array(
0=>array(
'text' => '儿歌三百首',
'grade' => '1'
)
)
),
1=>array(
'text' => '跳舞',
'grade' => '3'
)
)
)
),
1=>array(
0=>array(
'text' => '体育',
'children' => array(
0=>array(
'text' => '篮球',
'grade' => '2'
),
1=>array(
'text' => '排球',
'grade' => '5'
)
)
),
1=>array(
'text' => '音乐',
'children' => array(
0=>array(
'text' => '唱歌',
'children' => array(
0=>array(
'text' => '儿歌三百首',
'grade' => '4'
)
)
)
)
)
),
);
//要求:递归遍历原始多维数组,将重复键值合并并累加grade值,以及记录重复次数。如:体育->篮球,经过处理后grade值为1+2=3,重复个数则为2(注:多维数组层级不定)
//以下是想要的到的结果
$newarray = array(
0=>array(
0=>array(
'text' => '体育',
'children' => array(
0=>array(
'text' => '篮球',
'grade' => '3',
'count' => '2'
),
1=>array(
'text' => '足球',
'grade' => '3',
'count' => '1'
),
2=>array(
'text' => '排球',
'grade' => '5',
'count' => '1'
)
)
),
1=>array(
'text' => '音乐',
'children' => array(
0=>array(
'text' => '唱歌',
'children' => array(
0=>array(
'text' => '儿歌三百首',
'grade' => '5',
'count' => '2'
)
)
),
1=>array(
'text' => '跳舞',
'grade' => '3',
'count' => '1'
)
)
)
)
);
function untree($ar, $pid=0) {
$res = array();
foreach((array)$ar as $v) {
if(is_numeric(key($v))) {
$res = array_merge($res, untree($v));
continue;
}
if(! isset($v['pid'])) $v['pid'] = $pid;
&nb