PHP代码一直有效,直到我成为一个函数

Chr*_*ris 3 php arrays 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>';
Run Code Online (Sandbox Code Playgroud)

当我将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>';
Run Code Online (Sandbox Code Playgroud)

Oza*_*ray 5

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

function adj_tree($tree, $item)
Run Code Online (Sandbox Code Playgroud)

function adj_tree(&$tree, $item)
Run Code Online (Sandbox Code Playgroud)

这是因为您的代码$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
}
Run Code Online (Sandbox Code Playgroud)

你的foreach循环将是这样的:

foreach ($result as $item){
    $tree = adj_tree($tree, $item);
}
Run Code Online (Sandbox Code Playgroud)