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 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办