PHP code works until I make it a function

I have this code here that gives me the result I'm looking for, a beautifully formatted value 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){
        $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 foreach into such a function, 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>';
+3
source share
3 answers

Currently, the function creates 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.

function adj_tree($tree, $item){
    $id = $item['recordId'];
    $parent = $item['actionParent'];
    $tree[$id] = isset($tree[$id]) ? $item + $tree[$id] : $item;
    $tree[$parent]['_children'][] = &$tree[];
    return $tree;
}
//...
foreach ($result as $item){
    $tree = adj_tree($tree, $item);
}

2) pass the array by reference and edit the global version inside the function.

function adj_tree(&$tree, $item){
    $id = $item['recordId'];
    $parent = $item['actionParent'];
    $tree[$id] = isset($tree[$id]) ? $item + $tree[$id] : $item;
    $tree[$parent]['_children'][] = &$tree[];
}
+2
source

- $tree .

function adj_tree($tree, $item)

to

function adj_tree(&$tree, $item)

, $tree adj_tree $tree. , , adj_tree .

( ) , , :

function adj_tree($tree, $item) {
        $id = $item['recordId'];
        $parent = $item['actionParent'];
        $tree[$id] = isset($tree[$id]) ? $item + $tree[$id] : $item;
        $tree[$parent]['_children'][] = &$tree[];
        return $tree; // this is the line I have added
}

foreach :

foreach ($result as $item){
    $tree = adj_tree($tree, $item);
}
+5

try the following:

function adj_tree($tree, $item){
    global $tree;
    // ...

or

function adj_tree(&$tree, $item){
0
source

All Articles