通常,您可以使用对象的方法执行此操作(回调可以是函数或对象的方法;后者允许您维护状态)。像这样的东西(未经测试):
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中的引用类型)来维护状态(来自How to "flatten" a multi-dimensional array to simple one in PHP?):
$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);