求教:数据的格式话问题
数据源格式:
$data = array(
array('id' => 1,'pid' => 0,'name' => 'a'),
array('id' => 2,'pid' => 0,'name' => 'b'),
array('id' => 3,'pid' => 1,'name' => 'c'),
array('id' => 4,'pid' => 1,'name' => 'd'),
array('id' => 5,'pid' => 3,'name' => 'e'),
array('id' => 6,'pid' => 3,'name' => 'f'),
array('id' => 7,'pid' => 6,'name' => 'g'),
array('id' => 8,'pid' => 6,'name' => 'h'),
array('id' => 9,'pid' => 8,'name' => 'i'),
array('id' => 10,'pid' => 8,'name' => 'j'),
array('id' => 11,'pid' => 9,'name' => 'l'),
array('id' => 12,'pid' => 9,'name' => 'm'),
);
<?php
$data = array(
array('id' => 1,'pid' => 0,'name' => 'a'),
array('id' => 2,'pid' => 0,'name' => 'b'),
array('id' => 3,'pid' => 1,'name' => 'c'),
array('id' => 4,'pid' => 1,'name' => 'd'),
array('id' => 5,'pid' => 3,'name' => 'e'),
array('id' => 6,'pid' => 3,'name' => 'f'),
array('id' => 7,'pid' => 6,'name' => 'g'),
array('id' => 8,'pid' => 6,'name' => 'h'),
array('id' => 9,'pid' => 8,'name' => 'i'),
array('id' => 10,'pid' => 8,'name' => 'j'),
array('id' => 11,'pid' => 9,'name' => 'l'),
array('id' => 12,'pid' => 9,'name' => 'm'),
);
/********我是YD的分割线*************/
$pid = 1000000;
//$mark = 'c';
foreach ($data as $key => $value){
if ($value[pid] == $pid) {
$a[$value[name]] = $a;
unset($a[$mark]);
unset($a[$mark2]);
}else{
$a[$value[name]] = $value[name];
}
$pid = $value[pid];
$mark2 = $mark;
$mark = $value[name];
//$mark2 = $mark;
//unset($a[]);
}
print_r($a);
?>
Array
(
[m] => Array
(
[j] => Array
(
[h] => Array
(
[f] => Array
(
[d] => Array
(
[b] => Array
(
[a] => a
)
[c] => c
)
[e] => e
)
[g] => g
)
[i] => i
)
[l] => l
)
)
$data = array(Array
array('id' => 1,'pid' => 0,'name' => 'a'),
array('id' => 2,'pid' => 0,'name' => 'b'),
array('id' => 3,'pid' => 1,'name' => 'c'),
array('id' => 4,'pid' => 1,'name' => 'd'),
array('id' => 5,'pid' => 3,'name' => 'e'),
array('id' => 6,'pid' => 3,'name' => 'f'),
array('id' => 7,'pid' => 6,'name' => 'g'),
array('id' => 8,'pid' => 6,'name' => 'h'),
array('id' => 9,'pid' => 8,'name' => 'i'),
array('id' => 10,'pid' => 8,'name' => 'j'),
array('id' => 11,'pid' => 9,'name' => 'l'),
array('id' => 12,'pid' => 9,'name' => 'm'),
);
print_r(foo($data));
function foo($ar, $pid=0) {
$res = array();
foreach($ar as $v) {
if($v['pid'] == $pid) {
$t = foo($ar, $v['id']);
$res[$v['name']] = $t ? $t : $v['name'];
}
}
return $res;
}
[i] => Array
(
[l] => l
[m] => m
)
[j] => j
)
)
)
[d] => d
)
[b] => b
)
需要注意的是:你给出的期望结果是错误的!因为没有一个节点是
array('id' => 4,'pid' => 1,'name' => 'd')
的子孙