2014-09-26 97 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