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 8778497
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T19:33:13+00:00 2026-06-13T19:33:13+00:00

How to build a tree from an array in PHP knowing the rules that

  • 0

How to build a tree from an array in PHP knowing the rules that need to be followed to build the tree?

I don’t have any particular place in the code where I can find what’s really wrong
Anyway, the problems are probably related with the passing by reference I’m repeatedly using.
I did not use recursion because speed is really really important here. From the rules that the input array has (I have full control over them), this is possible, and faster, without recursion.

How it works:
As you transverse the array, each element’s [‘start_order’] is a bigger number than the previous [‘start_order’].
Every time that the next element’s [‘start_order’] is bigger than this element’s [‘start_order’] and the next element’s [‘end_order’] is smaller than this element’s [‘end_order’], then that element is a child of this element.
After that step, I must find all the children of that element (the one I just found that it it this element’s child).

Here’s my code.

<?php
ksort($treeArray);
$tree = array();
$stack = array();
reset($treeArray);
$currentParent = &$treeArray[key($treeArray)];
$tree[] = &$treeArray[key($treeArray)];

while(next($treeArray) !== false){

    if(current($treeArray)['start_order'] <= $currentParent['end_order']){
        if(current($treeArray)['end_order'] <= $currentParent['end_order']){
            // There's a child of the previous

            // push the new parent
            $stack[] = $currentParent;

            if(!isset($currentParent['children'])){
                $currentParent['children'] = array();
            }
            $currentParent['children'][] = &$treeArray[key($treeArray)];
            $currentParent = current($treeArray);

        }else{
            // Supposed not to happen. Log the problem.
        }
    }else /* if(current($treeArray)['start_order'] > $currentParent['end_order']) */{
        // Pop the child here, there are no more children.
        if(($popedElement = array_pop($stack)) === NULL){
            $tree[] = $currentParent;
        }else{
            $popedElement['children'][] = &$treeArray[key($treeArray)];
            $stack[] = $popedElement;
            $currentParent = current($treeArray);
        }
    }
}

?>

Example:

The input array of this can be something that structurally looks like this:

[1][child1][child1child1][child2][child2child1][child2child2][child2child3][2][child2child1]

which resolves into this tree:

[1]
    [child1]
        [child1child1]
    [child2]
        [child2child1]
        [child2child2]
        [child2child3]
[2]
    [child2child1]

And don’t forget that this order maintains. [child2child3] never appears before [child2child2], [2] never appears before [1]. In this analogy, is almost like when dealing with XML.

  • 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-13T19:33:14+00:00Added an answer on June 13, 2026 at 7:33 pm

    Found the problem here. The problem is related on how I treat the pass-by-reference while trying to solve this problem.

    Here’s the solution:

    $tree[] = &$treeArray[key($treeArray)];
    $currentParent = &$treeArray[key($treeArray)];
    next($treeArray);
    
    while(current($treeArray) !== false){
    
        if(current($treeArray)['start_order']['start_position'] <= $currentParent['end_order']['end_order']){
            if(current($treeArray)['end_order']['end_order'] <= $currentParent['end_order']['end_order']){
                // There's a child of the previous
    
                // push the new parent
                $stack[] = &$currentParent;
    
                $currentParent['children'][] = &$treeArray[key($treeArray)];
    
                $currentParent = &$treeArray[key($treeArray)];
            }else{
                // Supposed not to happen. Log the problem.
            }
            next($treeArray);
        }else /* if(current($treeArray)['start_order']['start_position'] > $currentParent['end_order']['end_order']) */{
            // Close previous element here. There are no more children.
    
            if(end($stack) === false){
                $currentParent = &$treeArray[key($treeArray)];
                $tree[] = &$treeArray[key($treeArray)];
    
                next($treeArray);
            }else{              
                $currentParent = &$stack[key($stack)];
                unset($stack[key($stack)]);
            }
        }
    }
    

    The main problem was actually the pass-by-reference which is different in PHP than it is in C.
    To solve this problem, I’m unable to use both push or pop php functions:
    The push because the $var[] operator is faster and using that function.
    The pop, because its return is a copy of what I had pushed before instead of the actual element I had pushed.

    Additionally, all variable assignments have to be explicitly made by reference (using the & character), so using current() for assignment is out of the question, instead I need to use the key() function like I did.

    I also had a small but important bug that forced me to change the “while” instruction. It now contains current() instead of next(). That’s only because after the pop of the stack I mustn’t move to the next element. I need to do another iteration before I move to the next one. This solves the bad nesting generated when there are multiple tags closing in the same place.

    Please note that this code is not optimized for speed.

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

Sidebar

Related Questions

I have to build a tree using the following data which comes from a
i am in a situation where i need to the build the tree from
I need to build a binary tree from a preorder bitstring (which is piped
I am trying to build an SWT Tree that has icons at the top
i need to build the same source tree twice, 1 - with normal cflags
I'm pulling data from my database that is as such (raw): long's streetWe’d tree
I have a project where I need to build and store large trees of
I'm trying to build a DOM tree from a xmlTextReaderPtr . In my final
I'm implementing segment tree from an array of data, and I also want to
I am trying to build a binary tree from a string input piped to

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.