For the sake of being able to search and index/sort an array
I have a large multidimensional array that I am trying to parse. Right now, I am simply using the CakePHP shell to do so, but any method will suffice. What I need to do, is take the array of parent/children/more children and create an array of id’s with the associated ‘Outline Number’
So for example:
1
1.1
1.2
1.2.1
1.2.2
1.2.3
And so forth.
Here is an example of my ‘Input Array’:
Array
(
[0] => Array
(
[AsapStructure] => Array
(
[id] => 1
[lft] => 30267
[rght] => 32774
[parent_id] =>
[wbs] =>
)
[children] => Array
(
[0] => Array
(
[AsapStructure] => Array
(
[id] => 2
[lft] => 30268
[rght] => 30773
[parent_id] => 1
[wbs] => 1
)
[children] => Array
(
[0] => Array
(
[AsapStructure] => Array
(
[id] => 3
[lft] => 30269
[rght] => 30382
[parent_id] => 2
[wbs] => 1.1
)
What I envisioned, was having a simple parsing mechanism that is self-recursive. An example of what I have developed is as follows:
<?php
var $structIndex = array();
private function __parseStruct( $toParse,$prefix = null ) {
$iterator = 0;
if ( $prefix )
$prefix = $prefix . '.';
foreach( $toParse as $datum ) {
$iterator++;
if ( $datum['AsapStructure']['id'] == 1 )
$this->structIndex[ 1 ] = NULL;
else
$this->structIndex[ $datum['AsapStructure']['id'] ] = $prefix . $iterator ;
$subiterator = 0;
foreach( $datum['children'] as $key => $data ) {
$subiterator++;
$this->structIndex[ $data['AsapStructure']['id'] ] = $prefix . $subiterator;
if ( ! empty( $datum['children'] ) ) {
$this->__parseStruct( $datum['children'], $subiterator );
}
}
}
return $this->structIndex;
}
?>
What I do, is I call this $this->__parseStruct( $data ) function and pass the array to it. The function then loops over the array, calling the function for the nested child arrays. I have that part working okay, I just can’t seem to get the logic correct for creating the ‘indexes’, that is the 1.1, 1.2, 1.2.1 and so forth.
So my target output would then be:
$array[ $rowid ] = [ 1.1 / 1.2 / 1.2.1 / 1.2.2 ] or any combination as such.
Any help is greatly appreciated.
I was on the right track, I was just adding an extra unnecessary step.
This solved the issue. However, due to the nature of my array, it was necessary for me to call the function initially by doing:
$this->__parseStruct( $data[0]['children'] );otherwise I ended up with a 1. prefixing every data element in the resulting array.