加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 21:42:03 所属栏目:PHP教程 来源:网络整理
导读:我在这里有这个代码,它给了我正在寻找的结果,一个格式很好的值树. $todos = $this-db-get('todos'); //store the resulting records $tree = array(); //empty array for storage $result = $todos-result_array(); //store results as arrays foreach ($res
我在这里有这个代码,它给了我正在寻找的结果,一个格式很好的值树.

$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}的本地副本,对其进行编辑,然后在函数关闭时丢弃该副本.

您有两种选择:

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[];
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读