Answer the question
In order to leave comments, you need to log in
How to write a tree (multidimensional array) to the base as strings?
There are a million examples on the net of how to display a tree from the database, and I could not find a single one on how to write a tree to the database.
I use the jQuery plugin jsTree, it allows you to build trees with unlimited nesting, as a result, after construction, it can return the entire tree as a json string, in php you can easily turn this into a multidimensional array.
And then you need to somehow bypass this array and write the tree to the database, I tried to write it, but I ran into a problem: when we went around the children of one of the branches and suddenly found out that this branch has brothers, I can’t return the desired value of the parent.
Here's what I managed to do: example.php
If you run the example, you can immediately see from the result that not all parents were set correctly, help me understand what is the reason?
The goal is to write it all down in such a simple way
---------------------------------
id | parent_id | name
---------------------------------
1 | 0 | node 1
---------------------------------
2 | 1 | node 1-1
---------------------------------
3 | 1 | node 1-2
---------------------------------
4 | 0 | node 2
---------------------------------
5 | 4 | node 2-1
---------------------------------
6 | 4 | node 2-2
---------------------------------
7 | 6 | node 2-2-1
---------------------------------
8 | 4 | node 2-3
---------------------------------
Answer the question
In order to leave comments, you need to log in
The error is that $curr_parent does not return to the previous value.
Usually recursive scripts are written like this:
function my_array_walk($array, $parent = 0) {
global $final_result;
foreach ($array as $item) {
$final_result[$parent][] = [
'id' => $item['data']['id'],
'name' => $item['text'],
'parent' => $parent,
];
if (count($item['children']) > 0) {
my_array_walk($item['children'], $item['data']['id']);
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question