2013-11-28 77 views
0

我有一個嵌套數組的一個大問題,它包含類別樹:遞歸函數來獲取編號類別的樹在PHP

Array(
[1] => Array 
    (
     [parent_id] => 0 
     [category_id] => 1 
     [name] => Auto-moto 
     [path] => Auto-moto 
     [children] => Array 
      (


       [4] => Array 
        (
         [parent_id] => 1 
         [category_id] => 4 
         [name] => Autodiely 
         [path] => Auto-moto/Autodiely 
         [children] => Array 
          (
           [5] => Array 
            (
             [parent_id] => 4 
             [category_id] => 5 
             [name] => Kabínové filtre pre automobily 
             [path] => Auto-moto/Autodiely/Kabínové filtre pre automobily 
             [children] => 
            ) 

我有一個遞歸函數來顯示它在HTML ul>李名單,但我想讓列表看起來像這樣:

1.Auto-moto 
1.1.Autodiely 
1.1.1.Kabínové filtre pre automobily 
1.1.2. xxxx 
1.2.YYY 
1.3.AAA 
2.New 
2.1.Sub.... 

這可能嗎?非常感謝您的幫助。

回答

1

使用遞歸。我的方法是遞歸地遍歷所有級別的數組,併爲每個級別將相應的代碼添加到「級別」鍵中。 這是一個例子:

$arr = array(
    'a' => array(

     'name' => 'a', 
     'children' => array(

      'aa' => array(
       'name' => 'aa', 
       'children' => array(

        'aaa' => array(
         'name' => 'aaa', 
        ), 
       ), 
      ), 

      'ab' => array(
       'name' => 'ab', 
       'children' => array(

        'aba' => array(
         'name' => 'aba', 
         'children' => array(

          'abaa' => array(
           'name' => 'abaa', 
          ), 

         ), 
        ), 
        'abb' => array(
         'name' => 'abb', 
        ), 
       ), 
      ), 
     ) 
    ), 
    'b' => array(
     'name' => 'b', 
     'children' => array(
      'ba' => array(
       'name' => 'ba', 
      ), 
      'bb' => array(
       'name' => 'bb', 
      ), 
     ) 
    ), 
); 

/** 
* To target array, for each level adds new field named 'level', with level deep number 
* @param type $array target array 
* @param type $level nested level number 
*/ 
function add_levels(&$array, $level){ 
    $i = 0; 
    foreach ($array as $key => &$value) { 
     $level_name = $level.++$i; 
     $value[ 'level' ] = $level_name; 

     if(array_key_exists('children', $value) and is_array($value[ 'children' ])){ 
      add_levels($value[ 'children' ], $level_name.'.'); 
     } 

    } 
} 

/** 
* Prints out array in required form 
* @param type $array 
*/ 
function draw_ordered($array){ 
    foreach ($array as $key => &$value) { 
     echo($value[ 'level' ].'.'. $value[ 'name' ].'<br />'); 
     if(array_key_exists('children', $value) and is_array($value[ 'children' ])){ 
      draw_ordered($value[ 'children' ]); 
     } 
    } 
} 

add_levels($arr); 
//print_r($arr); 

draw_ordered($arr); 
die(); 
+0

非常感謝,這個作品 – Shanoy