dshtze500055 2019-04-08 15:01
浏览 56
已采纳

将子数组值组合到数组中的单个数组中

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.

  • 写回答

1条回答 默认 最新

  • drls2738 2019-04-08 18:42
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 为啥画版图在Run DRC会出现Connect Error?可我Calibre的hostname和计算机的hostname已经设置成一样的了。
  • ¥20 网站后台使用极速模式非常的卡
  • ¥20 Keil uVision5创建project没反应
  • ¥15 mmseqs内存报错
  • ¥15 vika文档如何与obsidian同步
  • ¥15 华为手机相册里面的照片能够替换成自己想要的照片吗?
  • ¥15 陆空双模式无人机飞控设置
  • ¥15 sentaurus lithography
  • ¥100 求抖音ck号 或者提ck教程
  • ¥15 关于#linux#的问题:子进程1等待子进程A、B退出后退出(语言-c语言)