I have this code here which gives me the result I’m looking for, a nicely formatted tree of values.
$todos = $this->db->get('todos'); //store the resulting records
$tree = array(); //empty array for storage
$result = $todos->result_array(); //store results as arrays
foreach ($result as $item){
$id = $item['recordId'];
$parent = $item['actionParent'];
$tree[$id] = isset($tree[$id]) ? $item + $tree[$id] : $item;
$tree[$parent]['_children'][] = &$tree[];
}
echo '<pre>';
print_r($tree);
echo '</pre>';
When I put the code from the foreach into a function like so, I get an empty array. What am I missing?
function adj_tree($tree, $item){
$id = $item['recordId'];
$parent = $item['actionParent'];
$tree[$id] = isset($tree[$id]) ? $item + $tree[$id] : $item;
$tree[$parent]['_children'][] = &$tree[];
}
$todos = $this->db->get('todos'); //store the resulting records
$tree = array(); //empty array for storage
$result = $todos->result_array(); //store results as arrays
foreach ($result as $item){
adj_tree($tree, $item);
}
echo '<pre>';
print_r($tree);
echo '</pre>';
Right now the function is making a local copy of {$tree}, editing it and then discarding that copy when the function closes.
You have two options:
1) return the local copy of {$tree} and assign it to the global copy.
2) pass the array by reference and edit the global version within the function.