Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8081713
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T16:49:35+00:00 2026-06-05T16:49:35+00:00

Problem: I am trying to build a recursive tree using a function and data

  • 0

Problem:

I am trying to build a recursive tree using a function and data from a MySQL. However, the results are not as expected.

PHP code:

function buildTree($root, $next = array()) 
{
    // Sanitize input
    $root = (int) $root;

    // Do query
    $query = "SELECT CID, Item, Parent FROM betyg_category WHERE Status = '1' AND Parent = '{$root}'";
    $result = mysql_query($query) or die ('Database Error (' . mysql_errno() . ') ' . mysql_error());

    // Loop results
    while ($row = mysql_fetch_assoc($result)) 
    {
      $next[$row['CID']] = array (
                                'CID' => $row['CID'], 
                                'Item' => $row['Item'], 
                                'Parent' => $row['Parent'], 
                                'Children' => buildTree($row['CID'], $next)
                            );
    }

    // Free mysql result resource
    mysql_free_result($result);

    // Return new array
    return $next;
}

$testTree = buildTree(0);

echo "<xmp>".print_r($testTree, true)."</xmp>";

The table in the database look like this:

enter image description here

I would like the array to be like this:

Array
(
    [1] => Array
    (
        [CID] => 1
        [Item] => Litteratur
        [Parent] => 0
        [Children] => Array
            (
                [2] => Integration av källorna
                [3] => Belysning av egna resultat
                [4] => Referenser
            )

    )

    and so forth..
)

That is to say, for each parent => produce children, then move on to next parent, etc. Thank you in advance for any advice.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T16:49:36+00:00Added an answer on June 5, 2026 at 4:49 pm

    You do not need recursion here. In fact, it will be very inefficent since you end up with a SELECT N+1 issue. Just order the result set by parent:

    $query = "SELECT CID, Item, Parent FROM betyg_category WHERE Status = '1' ORDER BY Parent";
    $result = mysql_query($query);
    
    $tree = array();
    while($row = mysql_fetch_assoc($result)) {
        if($row['Parent'] == 0) {
            $row['Children'] = array();
            $tree[$row['CID']] = $row;
        } else {
            $tree[$row['Parent']]['Children'][] = $row;
        }
    }
    

    This will produce the following:

    Array
    (
        [1] => Array
            (
                [CID] => 1
                [Item] => Litteratur
                [Parent] => 0
                [Children] => Array
                    (
                        [0] => Array
                            (
                                [CID] => 2
                                [Item] => Integration av källorna
                                [Parent] => 1
                            )
    
                        [1] => Array
                            (
                                [CID] => 3
                                [Item] => Belysning
                                [Parent] => 1
                            )
    
                        [2] => Array
                            (
                                [CID] => 4
                                [Item] => Referenser
                                [Parent] => 1
                            )
    
                    )
    
            )
    
        [5] => Array
            (
                [CID] => 5
                [Item] => Validitet
                [Parent] => 0
                [Children] => Array
                    (
                        [0] => Array
                            (
                                [CID] => 6
                                [Item] => Huvudsyfte
                                [Parent] => 5
                            )
    
                    )
    
            )
    
    )
    

    If you only want the name of each children, change, use $tree[$row['Parent']]['Children'][] = $row['Item']; instead.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm having this problem. I'm trying to build an UITableView with data from a
I'm trying to build out a mysql database design for a project. The problem
I have a std::vector< tr1::shared_ptr<mapObject> > that I'm trying build from data contained in
I`m trying to build a application using the Fragment/Tabs and Pager from the android
I'm trying to build a tree of LI/UL elements from an interal object I
Just starting out using MVC3 and hit a problem trying to build a drop-down
Problem Solved - See bottom for solution notes I'm trying to build a simple
I was trying to build up a ProcessBuilder calling the ffmpeg binary. My problem
I just ran into a problem.. I'm trying to build a website at the
I am having a problem trying to use the prependTo() function in jQuery... for

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.