-4

I have this kind of adjacency list:

Binary tree

I need to sort it to this: 2, 7, 9, 10, 8, 16, 17, 11

Basiccaly I have table where I have stored posts with parent ids. I can have unlimited number of levels.

I need just algorithm or full code in PHP.

I tried to use variations of row/column prefixes and some recurrent functions.

5
  • That's a nice looking tree you have there, but it's not nice enough for us to do this for you. Stackoverflow is here to help you with specific coding issues. If you give it a shot yourself and come back with any issues you run across, we will be more than happy to help; however "I need just algorithm or full code in php" shows you've tried nothing and put in no research. Commented Nov 6, 2017 at 11:25
  • That doesn't look much like a binary tree to me. What you've got there is an adjacency list - there are plenty of guides about parsing one (either in PHP or pseudocode). Commented Nov 6, 2017 at 11:26
  • @iainn doesn't a binary tree "branch" off whereas an adjacency list is just a single "road"? This looks like a binary tree to me. Commented Nov 6, 2017 at 11:28
  • OP look at how this guy asked a similar question in regards to binary tree; stackoverflow.com/questions/5020738/… Commented Nov 6, 2017 at 11:29
  • 3
    A node in a binary tree can only have two child nodes, left and right. Commented Nov 6, 2017 at 11:29

1 Answer 1

0

Okay, i finally did it. I was idi*t.

public function makeTree($parent_id = 0, &$array = array())
{
   // Get results where parent_id == $parent_id
  $recepts = $this->recept->get()->where("parent_id =" . $parent_id);
   // Foreach through them
   foreach ($recepts as $recept) {
     // Add this to array
     array_push($array, $recept);
     // Repeat
     $this->makeTree($recept["id"], $array);
   }
   return $array;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.