Making changes on a different property of recursive function - php

I'm currently developing this code that traverse a hierarchical array which should compute the sub-total of a property called cur_compensation. My issue is that the changes I do is not getting save
private function computeSubTotal($hierarchy){
foreach($hierarchy["_children"] as $key => $value){
if(isset($value["_children"]))
{
static::computeSubTotal($value);
}
else{
foreach($hierarchy["_children"] as $employee){
$employee_cur_compensation = $employee["cur_compensation"] ?? 0;
if (!isset($hierarchy["cur_compensation"])) {
$hierarchy["cur_compensation"] = 0;
}
$hierarchy["cur_compensation"] += $employee_cur_compensation;
}
return $hierarchy;
}
}
return $hierarchy;
}
This is the function so what it does it goes to the deepest node, the deepest node is a value that does not have any _children which mean it doesn't have any sub department (the hierarchy is sorted that the sub department are always on top)
The issue I have, once it reaches the bottom it computes the cur_compensation by looping through the employees of that department and adding it on the department "cur_compensation" property.
The issue is that, it doesn't save any of my changes.
So the purpose of the function is to add up the 'cur_compensation' of each employee/sub-department.
For example ->
$rows = array(
array(
'name' => "Main",
'id' => 1,
'parent_id' => 0,
'cur_compensation' => 0,
'_children' => array(
array(
'name' => "Dept A",
'id' => 2,
'parent_id' => 1),
),
array(
'name' => "Dept B",
'id' => 3,
'parent_id' => 1,
'_children' => array(
array(
'name' => "Dept C",
'cur_compensation' => 30000,
'id' => 4,
'parent_id' => 3),
array(
'name' => "Employee C",
'cur_compensation' => 30000,
'id' => 7,
'parent_id' => 3
)
)),
array(
'name' => "Employee A",
'cur_compensation' => 20000,
'id' => 5,
'parent_id' => 1
),
array(
'name' => "Employee B",
'cur_compensation' => 30000,
'id' => 6,
'parent_id' => 1
)
)
)
);
The result I want to get would be:
$rows = array(
array(
'name' => "Main",
'id' => 1,
'parent_id' => 0,
'cur_compensation' => 120000,
'_children' => array(
array(
'name' => "Dept A",
'id' => 2,
'cur_compensation' => 0,
'parent_id' => 1),
),
array(
'name' => "Dept B",
'id' => 3,
'parent_id' => 1,
'cur_compensation' => 60000,
'_children' => array(
array(
'name' => "Dept C",
'cur_compensation' => 30000,
'id' => 4,
'parent_id' => 3),
array(
'name' => "Employee C",
'cur_compensation' => 30000,
'id' => 7,
'parent_id' => 3
)
)),
array(
'name' => "Employee A",
'cur_compensation' => 30000,
'id' => 5,
'parent_id' => 1
),
array(
'name' => "Employee B",
'cur_compensation' => 30000,
'id' => 6,
'parent_id' => 1
)
)
)
);
So you would notice that Main and Dept B got the cur_compensation based on the _children property

There's a few things to make note on here - so I'm going to add comments to your existing code, then provide an example of how you could change it.
(I've formatted the code in each case)
class Example {
// filler code so that we can call
public function process($array){
return $this->computeSubTotal($array);
}
private function computeSubTotal($hierarchy) {
// we're not checking whether "_children" property exists before looping on it
foreach ($hierarchy["_children"] as $key => $value) {
if (isset($value["_children"])) {
// we're calling the method, but not doing anything with the return value.
static::computeSubTotal($value);
// we can set the original array value instead which will provide a modified copy
// this can be resolved by uncommenting the line below
// $hierarchy["_children"][$key] = static::computeSubTotal($value);
// also note that if this "child" doesn't have any *grand*children
// then we won't get an updated value due to how this is structured
// to fix this, you could remove the else wrapping so that the code
// below runs always
} else {
// double looping - we're already looping this array
// this will cause the end value to increase exponentially
foreach ($hierarchy["_children"] as $employee) {
$employee_cur_compensation = $employee["cur_compensation"] ?? 0;
if (!isset($hierarchy["cur_compensation"])) {
$hierarchy["cur_compensation"] = 0;
}
$hierarchy["cur_compensation"] += $employee_cur_compensation;
}
// returning whole array inside the loop is not ideal
// we have already adjusted the main array
// comment out this return to prevent that from happening
return $hierarchy;
}
}
return $hierarchy;
}
}
$example = new Example;
// calling this on $rows won't give us anything back
// since $rows doesn't contain the property "_children"
$rows = $example->process($rows);
// in this case, you would want to process each array result
// only on this primary array
foreach($rows as $index => $value){
$rows[$index] = $example->process($value);
}
echo json_encode($rows, JSON_PRETTY_PRINT);
Taking those comments into account, you would end up with something like this:
private function computeSubTotal($hierarchy) {
// we're not checking whether "_children" property exists before looping on it
foreach ($hierarchy["_children"] as $key => $value) {
if (isset($value["_children"])) {
$hierarchy["_children"][$key] = static::computeSubTotal($value);
}
// double looping - we're already looping this array
// this will cause the end value to increase exponentially
foreach ($hierarchy["_children"] as $employee) {
$employee_cur_compensation = $employee["cur_compensation"] ?? 0;
if (!isset($hierarchy["cur_compensation"])) {
$hierarchy["cur_compensation"] = 0;
}
$hierarchy["cur_compensation"] += $employee_cur_compensation;
}
}
return $hierarchy;
}
That's closer but still, it's not quite correct due to the double looping.
I've made a simpler version that is hopefully easy to follow:
private function computeSubTotal($hierarchy) {
if (!isset($hierarchy["_children"])) {
return $hierarchy;
}
// define this outside the loop for clarity
if (!isset($hierarchy["cur_compensation"])) {
$hierarchy["cur_compensation"] = 0;
}
foreach ($hierarchy["_children"] as $key => $value) {
// don't need to check for "_children" property
// as it's now handled in this function
$updated = static::computeSubTotal($value);
// reference the $updated array to increment
// the "cur_compensation" field
$hierarchy["cur_compensation"] += $updated["cur_compensation"] ?? 0;
// update original array
$hierarchy["_children"][$key] = $updated;
}
return $hierarchy;
}
// call like
foreach ($rows as $index => $value) {
$rows[$index] = static::computeSubTotal($value);
}
You will still need to change how you're passing the $rows variable due to it now containing a "_children" property (as shown in the examples) - either pass each element or add additional logic in that function to handle that.

You need to pass the array as a reference.
https://www.php.net/manual/en/language.references.pass.php
PHP passes the array to the function as a pointer, but when you try to update the array, PHP first makes a full copy of the array and updates the copy instead of the original.
Change your function signature to the following and it should be good.
private function computeSubTotal(&$hierarchy){
P.S. You are calling computeSubTotal statically, but the function is not static itself.

Related

Recursive array parse with nested nodes

I have blackhole in my mind. Im trying to parse array with multilevel nodes. Here's example array:
global $array;
$array = [
'0' => [
'id' => 1,
'parent' => 0,
'name' => 'root 0'
],
'1' => [
'id' => 2,
'parent' => 1,
'name' => 'root 1'
],
'2' => [
'id' => 3,
'parent' => 2,
'name' => 'root 2'
],
'3' => [
'id' => 4,
'parent' => 3,
'name' => 'root 3'
],
'4' => [
'id' => 5,
'parent' => 3,
'name' => 'root 4'
],
'5' => [
'id' => 6,
'parent' => 2,
'name' => 'root 2'
]
];
This should looks after parse like this. Element 3 with parent 3 should have parent 1, because element 2 has parent 2, and its first child.
I trying to get to this using foreach and function:
global $new_array;
$new_array = [];
foreach( $array as $item )
{
if( $item['parent'] == 0 ) {
$new_array[] = $item; // if parent 0 - clone into new array
continue;
}
//echo $item['name'] . PHP_EOL;
$new_array[] = check_parent( $item['parent'] );
}
print_r($new_array);
function check_parent( $parent )
{
//echo '- check for parent of ' . $parent . PHP_EOL;
global $array;
foreach( $array as $item ) {
if( $item['id'] == $parent && $item['parent'] == 0 ) {
//echo '[OK] found root parent id: ' . $item['id'] . PHP_EOL;
$item['parent'] = $item['id'];
return $item;
} else {
return check_parent( $item['id'] );
}
}
}
I'm so confused, but I didn't see where I make a mistake. Maybe someone, can help me to see - where's problem. I working on it few hours and for now, I had blackhole in my mind.
Fiddle:
https://implode.io/jHS8m1
Desired output:
$new_array = [
'0' => [
'id' => 1,
'parent' => 0,
'name' => 'root 0'
],
'1' => [
'id' => 2,
'parent' => 1,
'name' => 'root 1'
],
'2' => [
'id' => 3,
'parent' => 2, // this should have after parse parent 1
'name' => 'root 2'
],
'3' => [
'id' => 4,
'parent' => 3, // this should have after parse parent 1
'name' => 'root 3'
],
'4' => [
'id' => 5,
'parent' => 3, // this should have after parse parent 1
'name' => 'root 4'
],
'5' => [
'id' => 6,
'parent' => 2, // this should have after parse parent 1
'name' => 'root 2'
]
];
Thanks !
Replace the following line in your code
$new_array[] = check_parent( $item['parent'] ); // get child
with below lines of code.
$temp = check_parent( $item['parent'] ); // get child
$item['parent'] = $temp['id'];
$new_array[] = $item;
What is happening is that your check_parent is returning the $item, which happens to be the parent. However, we are only interested in the id of this. So we get the id and replace the parent it in the original $item.
Here is the working Demo
A bit tardy in my response, but I think it is valuable to provide a refined recursive solution.
My snippet:
Modifies by reference
Does not leverage a global variable declaration
Uses just one loop in the custom recursive function.
Code: (Demo)
function replaceParent(&$array, $parent = null) {
foreach ($array as &$item) {
if ($item['id'] == $parent) {
if ($item['parent']) {
return replaceParent($array, $item['parent']);
} else {
return $item['id'];
}
} elseif ($item['parent']) {
$item['parent'] = replaceParent($array, $item['parent']);
}
}
}
replaceParent($array);
var_export($array);
I'll try to explain...
id 1's parent value of 0 fails both primary conditions, so no recursion/processing is performed on that row of data.
id 2's parent value of 1 passes the elseif condition, so the recursive call goes in search of the row with an id of 1. Finding id 1 with a parent value of 0 means the else branch is satisfied and the id value of 1 is passed back through the recursive call to be assigned to $item['parent'] for the original id 2.
To process id 3 (or deeper), multiple recursive calls occur and all conditions play a role in the search and assignment process. First the elseif leads to the first recursion, then the if's if leads to the second recursion, finally the if's else passes the root id's value all the way back to the original grandchild.

Call each value from array of an object

I have function in class, which returns array with 4 3-4 rows. I have to use each value from related row in table values. I can print builded function atrray, and can print on parent file, but can not get values for elements for each row. Here is my class file:
<?php
class Anyclass
{
public function $monthly($array)
{
.
.
.
}
public function myfunction($array)
{
foreach ($ShowMonths as $duration) {
$array['Credit']['downpayment'] = 0;
$array['Credit']['duration'] = $duration;
$monthly = $this->monthly($array);
$Table['Options'][] = array(
'downpayment' => $array['Credit']['downpayment'],
'duration' => $array['Credit']['duration'],
'monthly' => $monthly,
'total' => $monthly * $array['Credit']['duration'] + $array['Credit']['downpayment']
);
}
print_r($Table);
}
}
Here is my main file
include_once('mypathtofile/FileWithClass.php');
$Cll = new NewOne();
$array = array(
'Rule' => array(
'rule_id' => 1,
'rule_name' => 'Mobile phones',
'interest' => 0.01,
'comission' => 0.01,
'best_offer_downpayment' => 0.5,
'best_offer_duration' => 6
),
'Product' => array(
'product_id' => 1,
'category_id' => 1,
'manufacturer_id' => 1,
'product_price' => 500
),
'Credit' => array(
'downpayment' => 100,
'duration' => 6
)
);
$prtst = $Cll->myfunction($array);
How can I call each elemet for each row?
I'm not sure what you are trying to do, but if you need to get each value in a multidimensional array - you can use recursion:
function get_value($array){
foreach($array as $item){
if(is_array($item)){
get_value($item);
} else {
echo $item;
}
}
}

How to loop through array with indeterminate amount of children arrays

Im trying to list categories with sub categories in my app - I can use either PHP or Javascript / Jquery for the following:
I have an array of categories with sub categories appended as additional arrays
the trick is that it can go as deep as there are sub categories.
and sub categories can also have sub categories.
Therefore for each category it can have as many children each of whom can have many children arrays.
What would be the best way to loop through them to create a dropdown list?
Here is the structure when dumping the main array:
array (size=2)
0 =>
array (size=4)
'id' => int 1
'name' => string 'Stationery' (length=10)
'parent_id' => int 0
'childs' =>
array (size=1)
0 =>
array (size=4)
...
1 =>
array (size=3)
'id' => int 4
'name' => string 'boots' (length=5)
'parent_id' => int 0
notice sub zero has a "childs" array
when dumping this array i get:
array (size=1)
0 =>
array (size=4)
'id' => int 2
'name' => string 'pens' (length=4)
'parent_id' => int 1
'childs' =>
array (size=1)
0 =>
array (size=4)
...
Notice this too has a child attached which when dumped looks like:
array (size=1)
0 =>
array (size=4)
'id' => int 3
'name' => string 'penfillers' (length=10)
'parent_id' => int 2
'childs' =>
array (size=1)
0 =>
array (size=3)
...
Sneaky - this one also has another child!
This can go as deep as there are sub categories
How would i loop through them and have the output in a dropdown list?
Im stumped as to how to loop infinitely until the chain ends.
Thanks
Jason
You should recursively yield all the options in the array. There are 2 ways to implement it. Depends on your PHP version.
To make the core logic cleaner, let's say we'd render the output with these utilities:
//
// some function to tidy up outputs
//
// simply make the recursive level visible
function pad_level($string, $level) {
// no pad for 0 level
if ($level == 0) return $string;
// pad some '-' to show levels
$pad = str_repeat('-', $level);
return $pad . ' ' . $string;
}
// render a leaf into standardized info array for an option
function option_from($item, $level) {
return array(
'value' => $item['id'],
'display_value' => pad_level($item['name'], $level),
);
}
// render options into HTML select
function render_select($name, $options) {
$output = '';
foreach ($options as $option) {
$output .= ' '.
'<option value="'.htmlspecialchars($option["value"]).'">'.
htmlspecialchars($option["display_value"]).
'</option>'."\n";
}
return '<select name="'.htmlspecialchars($name).'">'."\n".
$output."</select>\n";
}
// render options into plain text display
function render_plain_text($name, $options) {
$output = '';
foreach ($options as $option) {
$output .= $option["value"].' => '.$option["display_value"]."\n";
}
return $output;
}
These are the 2 methods:
//
// core logic
//
// Method 1: Generator. Available with PHP 5 >= 5.5.0
function options_in($array, $level=0) {
foreach ($array as $leaf) {
yield option_from($leaf, $level);
// yield the children options, if any
if (isset($leaf['childs']) && is_array($leaf['childs'])) {
foreach (options_in($leaf['childs'], $level+1) as $option) {
yield $option;
}
}
}
}
// Method 2: Normal recursion then merge arrays. For PHP 4 or after
function get_options($array, $level=0) {
$output = array();
// yield for the option array
foreach ($array as $leaf) {
$output[] = option_from($leaf, $level);
// yield the children
if (isset($leaf['childs']) && is_array($leaf['childs'])) {
$childs = get_options($leaf['childs'], $level+1);
$output = array_merge($output, $childs); // this could be slow
}
}
return $output;
}
And this is how you actually render some HTML from it:
// dummy input
$input = array(
array(
'id' => 1,
'name' => 'Stationery',
'parent_id' => 0,
'childs' => array(
array(
'id' => 2,
'name' => 'Pencil',
'parent_id' => 1,
),
array(
'id' => 3,
'name' => 'Pen',
'parent_id' => 1,
),
array(
'id' => 5,
'name' => 'Notepad',
'parent_id' => 1,
'childs' => array(
array(
'id' => 8,
'name' => 'Blue Pad',
'parent_id' => 3,
),
array(
'id' => 9,
'name' => 'Red Pad',
'parent_id' => 3,
),
array(
'id' => 10,
'name' => 'iPad',
'parent_id' => 3,
),
),
),
),
),
array(
'id' => 4,
'name' => 'boots',
'parent_id' => 0,
),
);
// method 1, preferred
echo "\nMethod 1\n";
echo render_select('mySelect', options_in($input));
echo render_plain_text('mySelect', options_in($input));
// method 2
echo "\nMethod 2\n";
echo render_select('mySelect', get_options($input));
echo render_plain_text('mySelect', get_options($input));
Here is a really simple example of how you could do it using recursion. I'm sure there is better ways but this is a very simple function so you can see the concept. The function calls itself until the job is done (I'm using the square bracket array notation here so make sure your PHP version supports it)
<?php
function getItems(array $items)
{
$return = [];
foreach ($items as $item) {
$return[] = $item;
if (isset($item['childs']) && count($item['childs']) > 0) {
$return = array_merge(
$return,
getItems($item['childs'])
);
}
}
return $return;
}
$array = [
0 => [
'id' => 1,
'childs' => []
],
1 => [
'id' => 2,
'childs' => [
0 => [
'id' => 3,
'childs' => []
]
]
]
];
print_r(getItems($array));
Then just loop over the results to create your select options. Hope this helps
create a sub function, input of the sub function would be object ,this function will check if it is an array or a simple element, if it is an array then it will call the function again on that element else return the element.
just elaborate "Gerald Schneider"'s answer.

How to Print Binary Tree from the given Database Structure using PHP?

I have a MySQL database in this format :
table name : btree_mst
fields : id, parent_id, left_node_id, right_node_id, user_name
Now what I have to do is print it in the Un-ordered list format like below
Root Node
Node A
Node A Left
Node A Right
Node B
Node B Left
Node B Right
I tried to make a recursive function for that but didn't work as expected.
Any suggestions ?
Here is the Code I made, http://pastebin.com/X15qAKaA
The only bug in this code is, it is printing UL every time. It should print only when the Level is changed.
Thanks in advance.
If you do not have ordered list in your DB, recursion is suitable.
class A
{
private $a = array(
array(
'id' => 1,
'parent_id' => 0,
'title' => 'ROOT'
),
array(
'id' => 2,
'parent_id' => 1,
'title' => 'A'
),
array(
'id' => 3,
'parent_id' => 1,
'title' => 'B'
),
array(
'id' => 4,
'parent_id' => 2,
'title' => 'A left'
)
);//your database values
public function buildTree()
{
$aNodes = array();
$iRootId = 1;//your root id
foreach ($this->a AS $iK => $aV)
{
if($aV['id'] == $iRootId)
{
unset($this->a[$iK]);
$aNodes[$aV['id']] = $aV;
$aNodes[$aV['id']]['childs'] = $this->getChilds($aV['id']);
}
}
print_r($aNodes);//print tree
}
private function getChilds($iParentId)
{
$aChilds = array();
foreach ($this->a AS $iK => $aV)
{
if($aV['parent_id'] == $iParentId)
{
unset($this->a[$iK]);
$aChilds[$aV['id']] = $aV;
$aChilds[$aV['id']]['childs'] = $this->getChilds($aV['id']);
}
}
return $aChilds;
}
}
$o = new A();
$o->buildTree();

Convert PHP array to JSON tree

I have got a array in this format:
array(
array('id' => 1, 'parent_id' => null, 'name' => 'lorem ipsum'),
array('id' => 2, 'parent_id' => 1, 'name' => 'lorem ipsum1'),
array('id' => 3, 'parent_id' => 1, 'name' => 'lorem ipsum2'),
array('id' => 4, 'parent_id' => 2, 'name' => 'lorem ipsum3'),
array('id' => 5, 'parent_id' => 3, 'name' => 'lorem ipsum4'),
array('id' => 6, 'parent_id' => null, 'name' => 'lorem ipsum5'),
);
I have to convert this array to json object with this style:
var json = {
id: "1",
name: "loreim ipsum",
data: {},
children: [{
id: "2",
name: "lorem ipsum1",
data: {},
children: [{
id: "3",
name: "lorem ipsum2",
data: {},
children: [{
..............
How can i do this? Thanks.
My solution:
$data = array(
array('id' => 1, 'parent_id' => null, 'name' => 'lorem ipsum'),
array('id' => 2, 'parent_id' => 1, 'name' => 'lorem ipsum1'),
array('id' => 3, 'parent_id' => 1, 'name' => 'lorem ipsum2'),
array('id' => 4, 'parent_id' => 2, 'name' => 'lorem ipsum3'),
array('id' => 5, 'parent_id' => 3, 'name' => 'lorem ipsum4'),
array('id' => 6, 'parent_id' => null, 'name' => 'lorem ipsum5'),
);
$itemsByReference = array();
// Build array of item references:
foreach($data as $key => &$item) {
$itemsByReference[$item['id']] = &$item;
// Children array:
$itemsByReference[$item['id']]['children'] = array();
// Empty data class (so that json_encode adds "data: {}" )
$itemsByReference[$item['id']]['data'] = new StdClass();
}
// Set items as children of the relevant parent item.
foreach($data as $key => &$item)
if($item['parent_id'] && isset($itemsByReference[$item['parent_id']]))
$itemsByReference [$item['parent_id']]['children'][] = &$item;
// Remove items that were added to parents elsewhere:
foreach($data as $key => &$item) {
if($item['parent_id'] && isset($itemsByReference[$item['parent_id']]))
unset($data[$key]);
}
// Encode:
$json = json_encode($data);
Here's code to do what you need. It does not need the items to be in parent-children order in the array, but will finish faster if they are.
Please study the comments to understand what the code is doing and why; and if you still have questions, ask them too!
// Assume your array is $data
$root = new stdClass; // this is your root item
$objectMap = array(); // this holds objects indexed by their id
// Since we need to iterate over the array, but there may be no guarantee
// that an item's parent will be always encountered before the item itself,
// we loop as many times as needed, skipping items whose parent we have not
// yet seen. Hopefully we will see it later and be able to process these
// items in the next iteration.
while (!empty($data)) {
// Remember how many items there are when starting the loop
$count = count($data);
// Do the actual work!
foreach ($data as $key => $row) {
$parentId = $row['parent_id'];
if ($parentId === null) {
// We just met the root element
$current = $root;
}
else if (isset($objectMap[$parentId])) {
// We met an element with a parent that we have already seen
$current = new stdClass;
}
else {
// We met an element with an unknown parent; ignore it for now
continue;
}
// Put the current element on the map so that its children will
// be able to find it when we meet them
$objectMap[$row['id']] = $current;
// Add the item to its parent's children array
$objectMap[$parentId]->children[] = $current;
// Set the item's properties
$current->id = $row['id'];
$current->name = $row['name'];
$current->data = new stdClass; // always empty
$current->children = array();
// We successfully processed this, remove it (see why below!)
unset($data[$key]);
}
// OK, we looped over the array once. If the number of items has
// not been reduced at all, it means that the array contains only
// items whose parents do not exist. Instead of looping forever,
// let's just take what we are given and stop here.
if ($count == count($data)) {
break;
}
// If there are still items in $data, we will now iterate again
// in the hope of being able to process them in the next iteration
}
// All set! If $data is not empty now, it means there were items
// with invalid parent_ids to begin with.
$output = json_encode($root);
My take (I know an answer has been accepted, but I worked on this so I'm gonna post id =P)
// Test data
$data = array(
array('id' => 1, 'parent_id' => null, 'name' => 'lorem ipsum'),
array('id' => 2, 'parent_id' => 1, 'name' => 'lorem ipsum1'),
array('id' => 3, 'parent_id' => 1, 'name' => 'lorem ipsum2'),
array('id' => 4, 'parent_id' => 2, 'name' => 'lorem ipsum3'),
array('id' => 5, 'parent_id' => 3, 'name' => 'lorem ipsum4'),
array('id' => 6, 'parent_id' => null, 'name' => 'lorem ipsum5'),
);
// Randomize, because the data may not be in a top-down order
shuffle( $data );
// Parse and inspect the result
$builder = new TreeBuilder( $data );
echo '<pre>', print_r( $builder->getTree() ), '</pre>';
class TreeBuilder
{
protected $leafIndex = array();
protected $tree = array();
protected $stack;
function __construct( $data )
{
$this->stack = $data;
while( count( $this->stack ) )
{
$this->branchify( array_shift( $this->stack ) );
}
}
protected function branchify( &$leaf )
{
// Root-level leaf?
if ( null === $leaf['parent_id'] )
{
$this->addLeaf( $this->tree, $leaf );
}
// Have we found this leaf's parent yet?
else if ( isset( $this->leafIndex[$leaf['parent_id']] ) )
{
$this->addLeaf( $this->leafIndex[$leaf['parent_id']]['children'], $leaf );
} else {
// Nope, put it back on the stack
$this->stack[] = $leaf;
}
}
protected function addLeaf( &$branch, $leaf )
{
// Add the leaf to the branch
$branch[] = array(
'id' => $leaf['id']
, 'name' => $leaf['name']
, 'data' => new stdClass
, 'children' => array()
);
// Store a reference so we can do an O(1) lookup later
$this->leafIndex[$leaf['id']] = &$branch[count($branch)-1];
}
protected function addChild( $branch, $leaf )
{
$this->leafIndex[$leaf['id']] &= $branch['children'][] = $leaf;
}
public function getTree()
{
return $this->tree;
}
}

Categories