PHP代码一直有效,直到我把它变成一个函数


PHP code works until I make it a function

我这里有这段代码,它给了我想要的结果,一个格式良好的值树。

    $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>';

当我把foreach中的代码放入这样的函数中时,我得到一个空数组。我错过了什么?

    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>';

最简单的方法是通过引用将$tree传递给函数。考虑更改代码中的以下行

function adj_tree($tree, $item)

function adj_tree(&$tree, $item)

这是因为在您的代码中,$tree作为原始$tree的副本在函数adj_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);
}

现在,函数正在制作{$tree}的本地副本,对其进行编辑,然后在函数关闭时丢弃该副本。

你有两个选择:

1) 返回{$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;
}
//...
foreach ($result as $item){
    $tree = adj_tree($tree, $item);
}

2) 通过引用传递数组,并在函数中编辑全局版本。

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

试试这个:

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

function adj_tree(&$tree, $item){