Jump to content

Recommended Posts

I am trying to store all the elements of my tree in an array.My code produces multi dimensional array, but i want it to be one dimensional. How can i get it ?

 

Code:-

function tree_gather($node)   //Function to calculate count
  {
    $sql = "SELECT lchild,rchild FROM tree WHERE parent = '$node'";
    $execsql = mysql_query($sql);
    $array = mysql_fetch_array($execsql);
    
    if(!empty($array['lchild']) || !empty($array['rchild']))
    {
   
      $child[] = $array['lchild'];
      $child[] = $array['rchild'];
      $child[] = tree_gather($array['lchild']);
      $child[] = tree_gather($array['rchild']);
      
    } 
     return $child;
  } 

 

Result:-

Array
(
    [0] => 2
    [1] => 3
    [2] => Array
        (
            [0] => 4
            [1] => 5
            [2] => Array
                (
                    [0] => 10
                    [1] => 11
                    [2] => 
                    [3] => 
                )

            [3] => Array
                (
                    [0] => 8
                    [1] => 9
                    [2] => 
                    [3] => 
                )

        )

    [3] => Array
        (
            [0] => 7
            [1] => 6
            [2] => Array
                (
                    [0] => 15
                    [1] => 14
                    [2] => Array
                        (
                            [0] => 16
                            [1] => 17
                            [2] => 
                            [3] => 
                        )

                    [3] => 
                )

            [3] => Array
                (
                    [0] => 13
                    [1] => 12
                    [2] => 
                    [3] => 
                )

        )

)

 

Table: -

table.PNG

 

 

 

These line are causing your array to be multidimensional

      $child[] = tree_gather($array['lchild']);
      $child[] = tree_gather($array['rchild']);

You may want to use array_merge here. Rather than assign the result of tree_gather() to your $child array. As you have it at the mement you will always get a multidimensional array.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.