I'm working on a project using jstree and attempting to save it to my database.
I'm having difficulties understanding how to do this because the user is able to create as many nodes as they want, to an unlimited depth.
For example consider the following tree:
When this is posted to PHP the array is as follows. Note how the children
elements appear:
$tree[0]['id'] = 'loc1';
$tree[0]['text'] = 'Sector';
$tree[1]['id'] = 'loc2';
$tree[1]['text'] = 'Location';
$tree[1]['children'][0]['id'] = 'italy-1';
$tree[1]['children'][0]['text'] = 'Italy';
$tree[1]['children'][1]['id'] = 'poland-1';
$tree[1]['children'][1]['text'] = 'Poland';
$tree[2]['id'] = 'j1_1';
$tree[2]['text'] = 'abc';
$tree[2]['children'][0]['id'] = 'j1_2';
$tree[2]['children'][0]['text'] = 'def';
$tree[2]['children'][0]['children'][0]['id'] = 'france-1';
$tree[2]['children'][0]['children'][0]['text'] = 'France';
$tree[2]['children'][0]['children'][1]['id'] = 'germany-1';
$tree[2]['children'][0]['children'][1]['text'] = 'Germany';
$tree[3]['id'] = 'j1_5';
$tree[3]['text'] = 'zzz';
My problem is that I don't understand is how to loop through the 'children'
elements of the array - because the depth varies between each parent node. If it was only 1 level deep I could use 1 foreach
statement and then check on the presence of [n]['children']
and then loop over the items inside it.
To further complicate matters I am saving the data using CakePHP 2.x Tree behaviour. This requires me to specify the parent ID when saving child elements, which means I need to loop through the array in order. For example if I was saving 'France' (under 'abc' > 'def') it would have to be done like this:
$data['Tree']['parent_id'] = 'j1_2'; // ID of 'def'
$data['Tree']['name'] = 'France';
$this->Tree->save($data);
Can anyone advise on how to loop through this data without the need to nest multiple foreach
statements? I have read Is there a way to loop through a multidimensional array without knowing it's depth? but couldn't apply this or understand if/how it's relevant to what I'm trying to do.