Welcome Guest, Not a member yet? Register   Sign In
Recursively search a hierarchial array and return all ancestors
#1

Dear friends,
    I'm here to request your help about a recursive function that finds out all siblings and parents starting from the last child. (It will used for a menu).
Surfing into the forum I discovered a very niceful code that works perfectly but not getting siblings! In detail:
Code:
$hierarchy[] = array('id' => 1, 'parent_id' => 0, 'name' => 'root1');
$hierarchy[] = array('id' => 2, 'parent_id' => 0, 'name' => 'root2');
$hierarchy[] = array('id' => 3, 'parent_id' => 1, 'name' => 'root1-1');
$hierarchy[] = array('id' => 4, 'parent_id' => 1, 'name' => 'root1-2');
$hierarchy[] = array('id' => 5, 'parent_id' => 3, 'name' => 'root1-1-1');
$hierarchy[] = array('id' => 6, 'parent_id' => 2, 'name' => 'root2-1');

if( ! function_exists('find_pat'))
{
    function find_pat($a, $n, $key='name' ){
        $out = array();
        foreach ($a as $r){
            if ($r[$key] == $n){
                $out = find_pat($a, $r['parent_id'],'id');
                $out[]=$r;
            }
        }
        return $out;
    }
}

When you try to search "root1-2" for example, the code missing the element "root1-1" (sibling).
The result code is:
Code:
Array
(
    [0] => Array
        (
            [id] => 1
            [parent_id] => 0
            [name] => root1
        )

    [1] => Array
        (
            [id] => 4
            [parent_id] => 1
            [name] => root1-2
        )

)


Can I ask you an help for this? 
Cheers
Reply
#2

Infinite dynamic Multi-level nested category with Codeigniter and MySQL
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply




Theme © iAndrew 2016 - Forum software by © MyBB