我在另一个函数中有这个匿名函数 $build_tree ,它在 PHP 5.3 中运行良好
function nest_list($list) {
$index = array();
index_nodes($list, $index);
$build_tree = function(&$value, $key) use ($index, &$updated) {
if(array_key_exists($key, $index)) {
$value = $index[$key];
$updated = true;
todel($key); }
};
do {
$updated = false;
array_walk_recursive($list, $build_tree);
} while($updated);
return $list;
}
function index_nodes($nodes, &$index) {
foreach($nodes as $key => $value) {
if ($value) {
$index[$key] = $value;
index_nodes($value, $index);
}
}
}
如何将其转换为 PHP 5.2 兼容代码?
通常,您可以使用对象的方法来完成此操作(回调可以是函数,也可以是对象的方法;后者允许您维护状态)。像这样的东西(未测试):
class BuildTree {
public $index, $updated = false;
public function __construct($index) {
$this->index = $index;
}
function foo(&$value, $key) {
if(array_key_exists($key, $this->index)) {
$value = $this-.index[$key];
$this->updated = true;
todel($key); }
}
}
do {
$build_tree_obj = new BuildTree($index);
array_walk_recursive($list, array($build_tree_obj, 'foo'));
} while($build_tree_obj->updated);
然而,array_walk_recursive
有一个特殊功能,允许我们传递第三个参数,该参数将传递到函数的每次调用中。虽然值是按值传递的,但我们可以巧妙地使用对象(PHP 5 中的引用类型)来维护状态(从如何在 PHP 中将多维数组“展平”为简单数组? https://stackoverflow.com/questions/526556/):
$build_tree = create_function('&$value, $key, $obj', '
if(array_key_exists($key, $index)) {
$value = $index[$key];
$updated = true;
todel($key); }
');
do {
$obj = (object)array('updated' => false);
array_walk_recursive($list, $build_tree, $obj);
} while($obj->updated);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)