如何return数组的一个元素,由递归资助?
How to return an element of array, which finded by recursion?
所以,我有点小麻烦:
我有一个class,我们把它命名为"Menu",另外,我有一个数组,它为"Menu"提供了一个元素,它看起来像
class Menu {
private $_data = [];
public function __construct() {
$this->_data = array(
"Parent1" => array(
"Child1" => array(
"id" => 1,
"minQuantity" => x,
"maxQuantity" => x,
"cost" => x,
),
"Child2"...
),
"ParentX" => array(
"ChildXX"...
)
/* AND SO ON */
);
}
}
此外,在 "Menu" 中我有一个函数,它通过递归尝试找到 $this->_data 中具有指定值的元素,函数如下所示:
public function findChildById($parent = null, $id = null) {
foreach ($parent as $_parent => $_child) {
if (array_key_exists($id, $parent)) var_dump($parent);
if (is_array($_child)) $this->findChildById($_child, $id);
}
}
但是,当它找到需要的元素时,我尝试 return 它 - 结果总是 NULL。使用 var_dump 会导致明显的输出,我可以看到我到底需要什么,但我不能 return 来自函数的元素。我该怎么办?
由于您只尝试找到一个元素,因此将 return 值向上传递到递归堆栈应该就足够了。例如。像这样:
public function findChildById($parent = null, $id = null) {
foreach ($parent as $_parent => $_child) {
if (array_key_exists($id, $parent)) return $parent; //first return
if (is_array($_child)) {
$tmp = $this->findChildById($_child, $id);
if (!is_null($tmp)) return $tmp; //if a deeper step found sth. pass it up
}
}
}
你得到 NULL 的原因一定是,因为当代码没有到达 return 语句时,PHP 隐式地运行 return NULL。
所以,我有点小麻烦: 我有一个class,我们把它命名为"Menu",另外,我有一个数组,它为"Menu"提供了一个元素,它看起来像
class Menu {
private $_data = [];
public function __construct() {
$this->_data = array(
"Parent1" => array(
"Child1" => array(
"id" => 1,
"minQuantity" => x,
"maxQuantity" => x,
"cost" => x,
),
"Child2"...
),
"ParentX" => array(
"ChildXX"...
)
/* AND SO ON */
);
}
}
此外,在 "Menu" 中我有一个函数,它通过递归尝试找到 $this->_data 中具有指定值的元素,函数如下所示:
public function findChildById($parent = null, $id = null) {
foreach ($parent as $_parent => $_child) {
if (array_key_exists($id, $parent)) var_dump($parent);
if (is_array($_child)) $this->findChildById($_child, $id);
}
}
但是,当它找到需要的元素时,我尝试 return 它 - 结果总是 NULL。使用 var_dump 会导致明显的输出,我可以看到我到底需要什么,但我不能 return 来自函数的元素。我该怎么办?
由于您只尝试找到一个元素,因此将 return 值向上传递到递归堆栈应该就足够了。例如。像这样:
public function findChildById($parent = null, $id = null) {
foreach ($parent as $_parent => $_child) {
if (array_key_exists($id, $parent)) return $parent; //first return
if (is_array($_child)) {
$tmp = $this->findChildById($_child, $id);
if (!is_null($tmp)) return $tmp; //if a deeper step found sth. pass it up
}
}
}
你得到 NULL 的原因一定是,因为当代码没有到达 return 语句时,PHP 隐式地运行 return NULL。