Php 从分层数组生成平面数组的递归函数
在过去的一个小时里,我一直试图做的是一个函数,它可以让我生成一个相同页面的平面数组,但是孩子们前面有他们父母的标题 到目前为止,我能做的是得到1级的父级,我需要这背后的逻辑,我可以做代码,主要的一点是在选择菜单中有一个数组来获取 i、 e: 我的数组如下所示:Php 从分层数组生成平面数组的递归函数,php,arrays,recursion,Php,Arrays,Recursion,在过去的一个小时里,我一直试图做的是一个函数,它可以让我生成一个相同页面的平面数组,但是孩子们前面有他们父母的标题 到目前为止,我能做的是得到1级的父级,我需要这背后的逻辑,我可以做代码,主要的一点是在选择菜单中有一个数组来获取 i、 e: 我的数组如下所示: Array ( [0] => Array ( [object]=>menuObject [title]=>title [parent_id]=>parent_id
Array (
[0] => Array (
[object]=>menuObject
[title]=>title
[parent_id]=>parent_id
[children]=>array(
[0] => Array (
[object]=>menuObject
[title]=>title
[parent_id]=>parent_id
[children]=>''
)
)
)
);
我需要的阵列如下所示:
Array(
[14]=>'parent / sub / sub 1'
//[ID]=>[Title]
)
很长一段时间后,我想出了一个方法,用两个函数, 第一个用来展平数组,另一个用来找出路径,不过我必须查询数据库才能找到它
public function parseSelectArray($tree)
{
$return=array();
foreach ($tree as $key => $value) {
//The other function call to create the path
$return[$key]=Controller_Admin_Pages::createPath($key);
}
return empty($return) ? null : $return;
}
public function createPath($id) {
//Query the page, though I could get the value from the array.
$page=Model_Page::find($id);
if($page->idparent == 0) {
$name = $page->title;
return $name;
} else {
$name = $page->title;
return Controller_Admin_Pages::createPath($page->idparent). " / ".$name;
}
}
有趣的是,昨天有人尝试了完全相同的方法:这可能更适合你的需要谢谢,伙计们,我找到了
public function parseSelectArray($tree)
{
$return=array();
foreach ($tree as $key => $value) {
//The other function call to create the path
$return[$key]=Controller_Admin_Pages::createPath($key);
}
return empty($return) ? null : $return;
}
public function createPath($id) {
//Query the page, though I could get the value from the array.
$page=Model_Page::find($id);
if($page->idparent == 0) {
$name = $page->title;
return $name;
} else {
$name = $page->title;
return Controller_Admin_Pages::createPath($page->idparent). " / ".$name;
}
}