3v4l.org

run code in 300+ PHP versions simultaneously
<?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]; } }
Output for 5.6.0 - 5.6.28, 7.0.0 - 7.0.20, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.27, 8.2.0 - 8.2.17, 8.3.0 - 8.3.4
<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 ( ) ) )

preferences:
224.83 ms | 405 KiB | 229 Q