Recommandé : "Tutoriel vidéo PHP"
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | public function index()
{
$data = [
[
'id' =>1,
'parent_id' => 0,
'name' => '第一个'
],
[
'id' =>2,
'parent_id' => 0,
'name' => '第二个'
],
[
'id' =>3,
'parent_id' => 1,
'name' => '第三个'
],
];
$r = $this ->list_to_tree( $data );
dump( $r );
}
|
Copier après la connexion

#array vers l'arborescence#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | function list_to_tree( $list , $root = 0, $pk = 'id' , $pid = 'parent_id' , $child = 'children' ){
$tree = array ();
if ( is_array ( $list )) {
$refer = array ();
foreach ( $list as $key => $data ) {
$refer [ $data [ $pk ]] = & $list [ $key ];
}
foreach ( $list as $key => $data ) {
$parentId = 0;
if (isset( $data [ $pid ])) {
$parentId = $data [ $pid ];
}
if ((string) $root == $parentId ) {
$tree [] = & $list [ $key ];
} else {
if (isset( $refer [ $parentId ])) {
$parent = & $refer [ $parentId ];
$parent [ $child ][] = & $list [ $key ];
}
}
}
}
return $tree ;}
|
Copier après la connexion
#tree Convertir la structure en tableau#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | function tree_to_list( $tree = [], $children = 'children' ){
if ( empty ( $tree ) || ! is_array ( $tree )) {
return $tree ;
}
$arrRes = [];
foreach ( $tree as $k => $v ) {
$arrTmp = $v ;
unset( $arrTmp [ $children ]);
$arrRes [] = $arrTmp ;
if (! empty ( $v [ $children ])) {
$arrTmp = tree_to_list( $v [ $children ]);
$arrRes = array_merge ( $arrRes , $arrTmp );
}
}
return $arrRes ;}
|
Copier après la connexion
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!