Jump to content

How to get one dimensional array and not multidimensional array


Nuv

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.