Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to get Tree structure for array in php

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 265
    Comment on it

    Hello reader's I have created a conversion format that can convert array in tree structure. In this code i use while loop but you can either use the recursive also. So here is the function as below:-

    function treeze( &$a, $parent_key, $children_key )
    {
        $orphans = true; $i;
        while( $orphans )
        {
            $orphans = false;
            foreach( $a as $k=>$v )
            {
                // is there $a[$k] sons?
                $sons = false;
                foreach( $a as $x=>$y )
                if( isset($y[$parent_key]) and $y[$parent_key]!=false and $y[$parent_key]==$k )  
                { 
                    $sons=true; 
                    $orphans=true; 
                    break;
                }
    
                // $a[$k] is a son, without children, so i can move it
                if( !$sons and isset($v[$parent_key]) and $v[$parent_key]!=false )
                {
                    $a[$v[$parent_key]][$children_key][$k] = $v;
                    unset( $a[$k] );
                }
            }
        }
    }
    

    In the code above every key value have it's own id . Now in this function you have to send three params , First the Array, Second is parentID and last childrenKey

    Finally you can access the function as by code below:-

    treeze( $SendArray, 'ID', 'Key' );
    echo "<pre>"; print_r( $SendArray);
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: