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

时间:2011-06-10 15:26:52

标签: 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>';

当我将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>';

3 个答案:

答案 0 :(得分:5)

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

function adj_tree($tree, $item)

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);
}

答案 1 :(得分:2)

现在该函数正在制作{$ 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[];
}

答案 2 :(得分:0)

试试这个:

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

function adj_tree(&$tree, $item){