在使用 PHP 进行开发的过程中,无限分类是一个常见且重要的需求。为了方便使用和操作,我们通常将无限分类转化为数组形式。
//无限分类数据 $arr = [ [ 'id' => 1, 'name' => '电子产品' , 'pid' => 0], [ 'id' => 2, 'name' => '手机' , 'pid' => 1], [ 'id' => 3, 'name' => '电脑' , 'pid' => 1], [ 'id' => 4, 'name' => 'android手机' , 'pid' => 2], [ 'id' => 5, 'name' => 'ios手机' , 'pid' => 2], [ 'id' => 6, 'name' => '家用电器' , 'pid' => 0], ]; print_r($this->categoryToTree($arr)); //定义一个递归函数,将无限分类数据转换为数组形式 public function categoryToTree( $source , $parentId = 0) { $result = []; foreach ( $source as $key => $value ) { if ( $value [ 'pid' ] == $parentId ) { unset( $source [ $key ]); $children = $this->categoryToTree( $source , $value [ 'id' ]); if (! empty ( $children )) { $value [ 'children' ] = $children ; } $result [] = $value ; } } return $result ; }
最终效果: