2013-07-11 46 views
0

遞歸函數I具有以下的數組:該數組的腓上陣列樹視圖

Array 
(
    [1] => 0 
    [2] => 1 
    [3] => 2 
    [4] => 3 
    [5] => 1 
    [6] => 0 
) 

密鑰是唯一的,和值表示密鑰的父。 像父母的1 & 6是0,父母的2是1,因爲3是2 ....

我在寫一個遞歸函數,它將爲給定的父id找到一個樹視圖。 這裏是我的代碼:

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; 
    } 

我創建的功能給我造成了一個級別的深度。這個功能,如果我叫它爲$父的結果= 1($ childParent是上面定的數組)是:

Array 
(
    [1] => Array 
     (
      [0] => 2 
      [1] => 5 
     ) 

    [2] => Array 
     (
      [0] => 3 
     ) 

    [3] => Array 
     (
      [0] => 4 
     ) 

) 

餘米期待結果是這樣的:

Array 
     (
      [1] => Array 
       (
        [2] => Array 
         (
          [3] => Array 
           (
            [0] => 4 
           ) 
         ) 

       ) 
      [2] => 5 
     ) 

或東西,幫我創建一個樹形視圖。 預先感謝您。

+0

我不明白你是如何轉換的邏輯將原始數組添加到您的預期數組中。什麼4到底什麼是1 2 3? – DevZer0

回答

1

這你想要做什麼:

<?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); 

?> 
1

型號:

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; 
} 

}

觀點:

$menu = new Menu(); 
$menu_array = $menu->menu_array(); 
echo $menu->show_menu_array($menu_array);