There is an array associated with each other ( id = parent_id ).
parent_id specifies the id parent.
<?php $arr = [ [ 'id' => 1, 'parent_id' => 0, 'sysname' => 'AAA' ], [ 'id' => 2, 'parent_id' => 0, 'sysname' => 'BBB' ], [ 'id' => 3, 'parent_id' => 1, 'sysname' => 'AAA1' ], [ 'id' => 4, 'parent_id' => 3, 'sysname' => 'AAA11' ], [ 'id' => 5, 'parent_id' => 2, 'sysname' => 'BBB1' ] ]; function CreateTree( $array,$sub=0, $tab='' ) { $category=array(); if( $sub > 0 ) { $tab .= '-'; } foreach( $array as $v ) { if( $sub == $v['parent_id']) { $category[$v['id']]['id'] = $v['id']; $category[$v['id']]['parent_id'] = $v['parent_id']; $category[$v['id']]['sysname'] = $tab.$v['sysname']; $category += CreateTree($array, $v['id'], $tab); } } return $category; } The CreateTree function Draws a tree.
The following function reverses this tree array_reverse So that deduced parents starting with it along the hierarchy
function getNavParentsByNavId( $navTree, $id ) { $trees = array_reverse( $navTree ); $newArr = []; foreach( $trees as $tree ) { if( $tree['id'] == $id ) { $newArr[$tree['id']] = $tree['sysname']; while($current = current($trees)) { $next = next($trees); if($current['parent_id'] == $next['id']) { $newArr[$next['id']] = $next['sysname']; } } } next($trees); } return $newArr; } $navTree = CreateTree($arr); echo '<pre>'; print_r($navTree); print_r(getNavParentsByNavId($navTree, 4)); The getNavParentsByNavId function should output the part where id is equal to the passed value and after it has parents for it.
That is, the result should look like
AAA11 AAA1 AAA But something does not work.