3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php $categories = array( array('id'=>1,'name'=>'电脑','pid'=>0), array('id'=>2,'name'=>'手机','pid'=>0), array('id'=>3,'name'=>'笔记本','pid'=>1), array('id'=>4,'name'=>'台式机','pid'=>1), array('id'=>5,'name'=>'智能机','pid'=>2), array('id'=>6,'name'=>'功能机','pid'=>2), array('id'=>7,'name'=>'超级本','pid'=>3), array('id'=>8,'name'=>'游戏本','pid'=>3), ); $tree = array(); //第一步,将分类id作为数组key,并创建children单元 foreach($categories as $category){ $tree[$category['pid']] = $category; $tree[$category['pid']]['parent'] = array(); } echo '<pre>';print_r($tree); //第二部,利用引用,将每个分类添加到父类children数组中,这样一次遍历即可形成树形结构。 foreach ($tree as $k=>$item) { if ($item['pid'] != 0) { $tree[$item['pid']]['parent'][] = &$tree[$k]; } }
based on 2JiTv
Output for 5.6.0 - 7.3.0alpha1
<pre>Array ( [0] => Array ( [id] => 2 [name] => 手机 [pid] => 0 [parent] => Array ( ) ) [1] => Array ( [id] => 4 [name] => 台式机 [pid] => 1 [parent] => Array ( ) ) [2] => Array ( [id] => 6 [name] => 功能机 [pid] => 2 [parent] => Array ( ) ) [3] => Array ( [id] => 8 [name] => 游戏本 [pid] => 3 [parent] => Array ( ) ) )