代码如下:
主要是把数据分成二个数组
其中一个数组值为原数据指针
public function test()
{
$arr = array(
array("id" => 1 , "pid" => 0 , 'cat' => '名字1'),
array("id" => 2 , "pid" => 0 , 'cat' => '名字2'),
array("id" => 3 , "pid" => 1 , 'cat' => '名字3'),
array("id" => 4 , "pid" => 2 , 'cat' => '名字4'),
array("id" => 5 , "pid" => 1 , 'cat' => '名字5'),
array("id" => 6 , "pid" => 5 , 'cat' => '名字6'),
array("id" => 7 , "pid" => 5 , 'cat' => '名字7'),
array("id" => 8 , "pid" => 6 , 'cat' => '名字8'),
array("id" => 15 , "pid" => 8 , 'cat' => '名字9'),
array("id" => 9 , "pid" => 1 , 'cat' => '名字10'),
array("id" => 10 , "pid" => 0 , 'cat' => '名字11'),
array("id" => 11 , "pid" => 10 , 'cat' => '名字12'),
array("id" => 12 , "pid" => 11 , 'cat' => '名字13'),
array("id" => 13 , "pid" => 2 , 'cat' => '名字14'),
array("id" => 14, "pid" => 13 , 'cat' => '名字15')
);
$refer = [];
$tree = [];
foreach($arr as $k=>$v)
{
$refer[$v["id"]] = & $arr[$k]; //id arr[$k] 的地址
}
foreach($arr as $k=>$v)
{
$pid = $v["pid"];
if($pid == 0)
{
$tree[] = & $arr[$k];
}else{
if(isset($refer[$pid]))
{
$refer[$pid]["sub"][] = & $arr[$k]; //通过修改这个指针里的数据 同时tree里面的也改变了
}
}
}
dump($tree);
}