2014-09-26 98 views
1

我有以下陣列:PHP扁平化陣列和增加深度關鍵

Array 
(
    [0] => Array 
     (
      [id] => 2 
      [title] => Root 2 
      [description] => 
      [site_id] => 1 
      [parent_id] => 0 
      [created_at] => 
      [updated_at] => 
      [children] => Array 
       (
        [0] => Array 
         (
          [id] => 4 
          [title] => Child 2 
          [description] => 
          [site_id] => 1 
          [parent_id] => 2 
          [created_at] => 
          [updated_at] => 
          [children] => Array 
           (
            [0] => Array 
             (
              [id] => 6 
              [title] => Child 4 
              [description] => 
              [site_id] => 1 
              [parent_id] => 4 
              [created_at] => 
              [updated_at] => 
             ) 

           ) 

         ) 

       ) 

     ) 

    [2] => Array 
     (
      [id] => 7 
      [title] => Root 3 
      [description] => 
      [site_id] => 1 
      [parent_id] => 0 
      [created_at] => 
      [updated_at] => 
     ) 

) 

我想它壓扁爲類似以下內容:

Array 
(
    [0] => Array 
     (
      [id] => 2 
      [title] => Root 2 
      [description] => 
      [site_id] => 1 
      [parent_id] => 0 
      [created_at] => 
      [updated_at] => 
      [depth] => 0 
     ) 
    [1] => Array 
     (
      [id] => 4 
      [title] => Child 2 
      [description] => 
      [site_id] => 1 
      [parent_id] => 2 
      [created_at] => 
      [updated_at] => 
      [depth] => 1 
     ) 
    [2] => Array 
     (
      [id] => 6 
      [title] => Child 4 
      [description] => 
      [site_id] => 1 
      [parent_id] => 4 
      [created_at] => 
      [updated_at] => 
      [depth] => 2 
     ) 
    [3] => Array 
     (
      [id] => 7 
      [title] => Root 3 
      [description] => 
      [site_id] => 1 
      [parent_id] => 0 
      [created_at] => 
      [updated_at] => 
      [depth] => 0 
     ) 
) 

注「深度」鍵 - 這應指出原始陣列中元素有多深

自調用/遞歸函數沒有問題

任何想法?

+4

你有沒有對此做過任何嘗試?你在哪裏遇到問題? – 2014-09-26 17:57:44

回答

3
function flatten($elements, $depth) { 
    $result = array(); 

    foreach ($elements as $element) { 
     $element['depth'] = $depth; 

     if (isset($element['children'])) { 
      $children = $element['children']; 
      unset($element['children']); 
     } else { 
      $children = null; 
     } 

     $result[] = $element; 

     if (isset($children)) { 
      $result = array_merge($result, flatten($children, $depth + 1)); 
     } 
    } 

    return $result; 
} 

//call it like this 
flatten($tree, 0); 
+0

謝謝這是非常有幫助的 - 非常類似於我的,但我深深地感到困惑...再次感謝 – 2014-09-26 18:33:10