A
A
Andrey Boychenko2018-12-13 15:46:14
PHP
Andrey Boychenko, 2018-12-13 15:46:14

How to find the root element?

There is an array:

$array = [
            0 => [
                "id" => 1,
                "parent" => 0
            ],
            1 => [
                "id" => 2,
                "parent" => 1
            ],
            2 => [
                "id" => 3,
                "parent" => 2
            ],
            3 => [
                "id" => 4,
                "parent" => 2
            ],
            4 =>[
                "id" => 5,
                "parent" => 2
            ],
            5 =>[
                "id" => 6,
                "parent" => 2
            ],
            6 =>[
                "id" => 7,
                "parent" => 1
            ],
            7 =>[
                "id" => 8,
                "parent" => 7
            ],
            8 =>[
                "id" => 9,
                "parent" => 7
            ],
            9 => [
                "id" => 10,
                "parent" => 7
            ],
            10 => [
                "id" => 11,
                "parent" => 7
            ],
            11 => [
                "id" => 12,
                "parent" => 0
            ]
        ];

Sort of here, a category is a subcategory, but the nesting can be unlimited. I need to find the root element for an entire branch. For example, for an element with index 3, the element with index 0 will be the root element. In fact, by passing the id function of absolutely any category, I want to get one single id of the root category for the entire branch.
Please help me with the implementation and explanation of what is happening. From what I've read, this can be solved with both recursion and while. But what to do in general and how to properly approach this, I can’t imagine.

If possible, please describe the solution to this problem in several ways and explain along the way what is happening and where, and which of the implementations is preferable. I want to understand how it works and is arranged.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2018-12-13
@Ka4_Piton

function getRootItem($id, $array) {
  foreach ($array as $item) {
    if ($item['id'] === $id) {
      $parent = $item['parent'];
      return $parent === 0 ? $item : getRootItem($parent, $array);
    }
  }

  return null;
}

A
Andrey, 2018-12-13
@VladimirAndreev

if the tree has one vertex, I would reindex this array into an array of the form
element_id => parent_id.
in the end, you get the element id, extract the parent, then its parent, then it, and so on, until you get to the element whose parent is 0. in the process, writing all the ids to an array.
all...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question