Search code examples
phparrayssub-array

Combine Sub-array values into a single array withing an array


I may not word this issue properly, so here's what am trying to achieve.

array { 
    [0]=> { 
        ["Abilities"]=> { ["Numerical"]=> 3 } 
    } 
    [1]=> { 
        ["Abilities"]=> { ["Verbal"]=> 1 } 
    } 
    [2]=> { 
        ["Domain"]=> { ["Programming"]=> 0 } 
    } 
} 

to

array { 
    [0]=> { 
        ["Abilities"]=> { ["Numerical"]=> 3 ["Verbal"]=> 1 } 
    } 
    [1]=> { 
        ["Domain"]=> { ["Programming"]=> 0 } 
    } 
} 

I get this array from an external source so I need optimized this way to use it.


Solution

  • The array you're getting from an external source is like a set of separate branches you need to merge into a single tree. You can use a recursive function to create the "optimized" structure you're going for. A recursive approach should work regardless of the depth of each branch.

    function merge_branches(array $branches): array
    {
        $merge = function ($node, &$tree) use (&$merge) {
            if (is_array($value = reset($node))) {
                $merge($value, $tree[key($node)]);        // merge branch node recursively
            } else {
                $tree[key($node)] = $value;               // set leaf node to value
            }
        };
    
        $tree = [];
        foreach ($branches as $branch) {
            $merge($branch, $tree);
        }
        return $tree;
    }
    
    $optimized = merge_branches($external);