So I have an associative array that's been passed via JQuery to my PHP page that contains the structure of a menu. This effectively comes in as something like this:
[{"id":1,"children":[{"id":2,"children":[{"id":3},{"id":4}]},{"id":5}]}]
I've decoded the string and made it into an associative array using json_decode like so:
$cleanJSON = json_decode($JSON,true);
This is all fine so far and gives the result like this:
Array (
[0] => Array
(
[id] => 1
[children] => Array
(
[0] => Array
(
[id] => 2
[children] => Array
(
[0] => Array
(
[id] => 3
)
[1] => Array
(
[id] => 4
)
)
)
[1] => Array
(
[id] => 5
)
)
)
)
The problem I'm having is I now need to figure out the left and right nested set values of each item so that I can update my database with this new structure.
The reason I'm doing this is to allow me to accomplish reordering menu items within the nested set model.
Getting a resulting array which looks something like the below example would be perfect:
Array (
[0] => Array
(
[id] => 1
[left] => 1
[right] => 10
)
[1] => Array
(
[id] => 2
[left] => 2
[right] => 7
)
[2] => Array
(
[id] => 3
[left] => 3
[right] => 4
)
[3] => Array
(
[id] => 4
[left] => 5
[right] => 6
)
[4] => Array
(
[id] => 5
[left] => 8
[right] => 9
)
)
The below code is a mess and doesn't work at all, but it's as far as I got with it:
$i_count = 1;
$i_index = 1;
$a_newTree;
function recurseTree($nestedSet)
{
global $i_count;
global $a_newTree;
$i_left = $i_count;
$a_newTree[$i_count-1]['left'] = $i_left;
$i_count++;
foreach ($nestedSet AS $key => $value)
{
if ($value['children'])
{
foreach($value['children'] as $a_child)
{
recurseTree($a_child); // traverse
}
}
}
$i_right=$i_count; // right = count
$a_newTree[$i_count-1]['right'] = $i_right;
$i_count++; // count+1
}
Any help appreciated!