This should works
$stack = array();
$arraySet = array();
foreach( $arrData as $intKey=>$arrValues) {
$stackSize = count($stack); //how many opened tags?
while($stackSize > 0 && $stack[$stackSize-1]['close'] < $arrValues['open']) {
array_pop($stack); //close sibling and his childrens
$stackSize--;
}
$link =& $arraySet;
for($i=0;$i<$stackSize;$i++) {
$link =& $link[$stack[$i]['index']]["children"]; //navigate to the proper children array
}
$tmp = array_push($link, array ('item'=>$arrValues,'children'=>array()));
array_push($stack, array('index' => $tmp-1, 'close' => $arrValues['close']));
}
return $arraySet;
I skip parametrized open and close tags but you can simply add it.
EDIT
What is happening here:
First the $stack
is empty so we skip while()
.
Then we assign reference to $arraySet
to the $link
, because $stack
is empty we push first element to $link
which is reference to $arraySet
. array_push()return 1 because this is the new length of
$arraySet
Next we add an element to the
$stackwhit values
('index' => 0, 'close' => 10)`
Next element:
Now $stack
has 1 element, but $stack[0]['close']
is greater than $arrValues['open']
for element so we skip while.
Again we set reference to $arraySet
to $link
but now there is on element in $stack
so we assign $link[$stack[0]['index']]["children"]
reference to $link so now $link
is pointing to $arraySet[0]["children"]
.
Now we push element to this children array. $tmp
gives us size of this children array and we push proper element to the stack.
Next element: It looks exactly like second one but at the beginning we pop one element from stack. So after this iteration on stack are two elements
('index' => 0, 'close' => 10)
('index' => 0, 'close' => 8)
Next element:
There is two element on stack but both have greater close
attribute then $arrValues['open']
so we skip while loop. Then in navigation part:
$link
is pointing to$arraySet
- then to
$arraySet[0]["children"]
- then to
$arraySet[0]["children"][0]["children"]
And we push element to this array. And so on...