gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 00:26:08 24 4
gpt4 key购买 nike

我这里有这段代码,它给了我正在寻找的结果,一个格式良好的值树。

    $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 传递给函数by reference .考虑更改代码中的以下行

function adj_tree($tree, $item)

function adj_tree(&$tree, $item)

这是因为在您的代码中,$tree 作为原始 $tree 的副本在函数 adj_tree 中传递。当您通过引用传递时,将传递原始的,并且函数 adj_tree 对其进行的更改会在调用后反射(reflect)出来。

第二个(不是首选)替代方案是让您的函数返回修改后的树,这样您的函数将如下所示:

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

关于PHP 代码一直有效,直到我将它变成一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6308530/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com