Answer the question
In order to leave comments, you need to log in
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
]
];
Answer the question
In order to leave comments, you need to log in
function getRootItem($id, $array) {
foreach ($array as $item) {
if ($item['id'] === $id) {
$parent = $item['parent'];
return $parent === 0 ? $item : getRootItem($parent, $array);
}
}
return null;
}
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 questionAsk a Question
731 491 924 answers to any question