[英]Php Recursive function on array for tree view
I have following array: 我有以下数组:
Array
(
[1] => 0
[2] => 1
[3] => 2
[4] => 3
[5] => 1
[6] => 0
)
keys of this array is unique, and values showing parent of key. 此数组的键是唯一的,并且值显示键的父级。 like parent of 1 & 6 is 0, parent of 2 is 1, for 3 is 2....
像1和6的父母是0,2的父母是1,3是2 ....
I was writing a recursive function which will find a tree view for given parent id. 我正在编写一个递归函数,它将找到给定父ID的树视图。 here is my code:
这是我的代码:
function recurviceChild($parent, $childParent, $resultArr = array()) {
foreach ($childParent as $key => $parentId) {
if ($parent == $parentId) {
$resultArr[$parentId][] = $key;
$resultArr = $this->recurviceChild($key, $childParent, $resultArr);
}
}
return $resultArr;
}
The function I created give me result for depth of level one. 我创建的函数给出了第一级深度的结果。 result of this function if i call it for $parent=1 ($childParent is array given above) is:
这个函数的结果,如果我为$ parent = 1调用它($ childParent是上面给出的数组)是:
Array
(
[1] => Array
(
[0] => 2
[1] => 5
)
[2] => Array
(
[0] => 3
)
[3] => Array
(
[0] => 4
)
)
I m expecting result like this: 我期待这样的结果:
Array
(
[1] => Array
(
[2] => Array
(
[3] => Array
(
[0] => 4
)
)
)
[2] => 5
)
or something that help me to create a tree view. 或者帮助我创建树视图的东西。 Thank you in advance.
先感谢您。
This does what you want: 这样做你想要的:
<?php
$a= array
(
1 => 0,
2 => 1,
3 => 2,
4 => 3,
5 => 1,
6 => 0
);
class node {
var $children;
public function __construct(){
$this->children = array();
}
}
$tree = array();
foreach ($a as $q => $p){
if(!isset($tree[$p]))
$tree[$p] = new node;
if(!isset($tree[$q]))
$tree[$q] = new node;
$mark[$p]=FALSE;
$mark[$q]=FALSE;
array_push($tree[$p]->children,$q);
}
function dfs(&$ans,$node){
global $tree, $mark;
$mark[$node] = TRUE;
$ans = array();
foreach($tree[$node]->children as $child)
if(!$mark[$child]){
$ans[$child]=$child;
dfs($ans[$child],$child);
}
}
$parent=1;
dfs($ans,$parent);
print_r($ans);
?>
model: 模型:
class Menu extends CI_Model {
public function __construct() {
parent::__construct();
}
public function menu_array($parent = 0) {
$items = array();
$this->db->where('parent', $parent);
$results = $this->db->get('os_menu')->result();
foreach($results as $result) {
$child_array = $this->menu_array($result->id);
if(sizeof($child_array) == 0) {
array_push($items, $result);
} else {
array_push($items, array($result, $child_array));
}
}
return $items;
}
public function show_menu_array($array){
$output = '<ul>';
foreach ($array as $key => $mixedValue) {
if (is_array($mixedValue)) {
$output .= '<li>' . $this->show_menu_array($mixedValue) . '</li>';
} else {
$output .= '<li>' . $mixedValue->name . '</li>';
}
}
$output .= '</ul>';
return $output;
}
} }
view: 视图:
$menu = new Menu();
$menu_array = $menu->menu_array();
echo $menu->show_menu_array($menu_array);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.