2015-10-23 89 views
0

考慮以下數組的父節點:獲取路徑(父/子)陣列

array(..) { 
    [1111]=> 
    &array(3) { 
    ["category_id"]=> 
    int(1111) 
    ["parent_id"]=> 
    int(0) 
    ["children"]=> 
    array(2) { 
     [2222]=> 
     &array(3) { 
     ["category_id"]=> 
     int(2222) 
     ["parent_id"]=> 
     int(1111) 
     ["children"]=> 
      array(2) { 
      [5555]=> 
       &array(1) { 
       ["category_id"]=> 
       int(5555) 
       ["parent_id"]=> 
       int(2222) 
       } 
     } 
     [3333]=> 
     &array(2) { 
     ["category_id"]=> 
     int(3333) 
     ["parent_id"]=> 
     int(1111) 
     } 
    } 

假設數組深度是未知的,我怎麼能確定的路徑,父節點?

例如,對於category_id = 5555,我應該得到以下結果:0, 1111,2222。對於category_id = 3333這將是0,1111

回答

1

一種方法:

function findParent($node, $array, &$parents) { 
    if (array_key_exists($node, $array)) { 
     $parents[] = $array[$node]['parent_id']; 
    } 
    else { 
     foreach ($array as $item) { 
      if (array_key_exists('children', $item)) { 
       $parents[] = $item['parent_id']; 
       findParent($node, $item['children'], $parents); 
      } 
     } 
    } 
} 

findParent(5555, $A, $parents);