You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP深度嵌套数组合并与数值求和问题求助

嵌套PHP数组合并:数值求和,字符串保留

我有一个由约33万字符JSON转换而来的PHP数组,数据结构稳定,最多3层嵌套。需要合并2到30组这类数组:仅对数值类型元素求和,字符串类型元素保持原样。目前尝试的代码返回空数组,无法实现嵌套数组的数值求和。

示例数据

两组不同日期的报表,每日用户信息一致,但嵌套的affiliates和users数组顺序可能不同:

// 今日报表
$reportToday = [
    'currentUser' => [
        'id' => '33',
        'username' => 'Will',
        'userProfile' => [
            'id' => '2',
            'user_id' => '33',
        ]
    ],
    'report' => [
        'commission' => [
            'total' => [
                'commission' => 1001,
                'profit' => 40,
                'sessions_total' => 200
            ],
            'users' => [
                'rob@gmail.com' => [
                    'commission' => 500.50,
                    'profit' => 20,
                    'sessions_total' => 100,
                    'affiliates' => [
                        'abc' => [
                            'commission' => 250.25,
                            'profit' => 10,
                            'sessions_total' => 50
                        ],
                        'xyz' => [
                            'commission' => 250.25,
                            'profit' => 10,
                            'sessions_total' => 50
                        ]
                    ]
                ],
                'joe@gmail.com' => [
                    'commission' => 500.50,
                    'profit' => 20,
                    'sessions_total' => 100,
                    'affiliates' => [
                        'xyz' => [
                            'commission' => 250.25,
                            'profit' => 10,
                            'sessions_total' => 50
                        ],
                        'abc' => [
                            'commission' => 250.25,
                            'profit' => 10,
                            'sessions_total' => 50
                        ]
                    ]
                ]
            ]
        ]   
    ]
];

// 昨日报表
$reportYesterday = [
    'currentUser' => [
        'id' => '33',
        'username' => 'Will',
        'userProfile' => [
            'id' => '2',
            'user_id' => '33',
        ]
    ],
    'report' => [
        'commission' => [
            'total' => [
                'commission' => 1001,
                'profit' => 40,
                'sessions_total' => 200
            ],
            'users' => [
                'joe@gmail.com' => [
                    'commission' => 500.50,
                    'profit' => 20,
                    'sessions_total' => 100,
                    'affiliates' => [
                        'abc' => [
                            'commission' => 250.25,
                            'profit' => 10,
                            'sessions_total' => 50
                        ],
                        'xyz' => [
                            'commission' => 250.25,
                            'profit' => 10,
                            'sessions_total' => 50
                        ]
                    ]
                ],
                'rob@gmail.com' => [
                    'commission' => 500.50,
                    'profit' => 20,
                    'sessions_total' => 100,
                    'affiliates' => [
                        'abc' => [
                            'commission' => 250.25,
                            'profit' => 10,
                            'sessions_total' => 50
                        ],
                        'xyz' => [
                            'commission' => 250.25,
                            'profit' => 10,
                            'sessions_total' => 50
                        ]
                    ]
                ]
            ]
        ]   
    ]
];

当前尝试的代码

这段代码返回空数组,无法处理嵌套结构:

$combinedReport = array();

foreach (array_keys($reportToday + $reportYesterday) as $report) {
    $sums[$report] = (isset($reportToday[$report]) ? $reportToday[$report] : 0) + (isset($reportYesterday) ? $reportYesterday[$report] : 0);
}

var_dump($combinedReport); 

期望的合并结果

保留数据完整性,数值求和,字符串保持原样:

// 合并后的目标结果
$combined = [
    'currentUser' => [
        'id' => '33',
        'username' => 'Will',
        'userProfile' => [
            'id' => '2',
            'user_id' => '33',
        ]
    ],
    'report' => [
        'commission' => [
            'total' => [
                'commission' => 2002,
                'profit' => 80,
                'sessions_total' => 400
            ],
            'users' => [
                'joe@gmail.com' => [
                    'commission' => 1001,
                    'profit' => 40,
                    'sessions_total' => 200,
                    'affiliates' => [
                        'abc' => [
                            'commission' => 500.50,
                            'profit' => 20,
                            'sessions_total' => 100
                        ],
                        'xyz' => [
                            'commission' => 500.50,
                            'profit' => 20,
                            'sessions_total' => 100
                        ]
                    ]
                ],
                'rob@gmail.com' => [
                    'commission' => 1001,
                    'profit' => 40,
                    'sessions_total' => 200,
                    'affiliates' => [
                        'abc' => [
                            'commission' => 500.50,
                            'profit' => 20,
                            'sessions_total' => 100
                        ],
                        'xyz' => [
                            'commission' => 500.50,
                            'profit' => 20,
                            'sessions_total' => 100
                        ]
                    ]
                ]
            ]
        ]   
    ]
];

解决方案:递归合并函数

针对嵌套数组结构,用递归遍历处理是最可靠的方式。以下代码支持合并任意数量的数组,自动对数值类型求和,字符串类型保留原数据(因每日用户信息一致,直接取第一个数组的字符串值):

// 处理两个嵌套数组的合并逻辑
function mergeNestedArrays($arr1, $arr2) {
    $merged = $arr1;
    
    foreach ($arr2 as $key => $value) {
        if (isset($merged[$key]) && is_array($merged[$key]) && is_array($value)) {
            // 递归合并嵌套子数组
            $merged[$key] = mergeNestedArrays($merged[$key], $value);
        } elseif (isset($merged[$key]) && is_numeric($merged[$key]) && is_numeric($value)) {
            // 数值类型元素求和
            $merged[$key] += $value;
        } else {
            // 非数值类型或仅存在于单个数组的元素,保留原数据(优先取第一个数组的值)
            $merged[$key] = $merged[$key] ?? $value;
        }
    }
    
    return $merged;
}

// 支持合并任意数量报表的入口函数
function mergeReports(...$reports) {
    if (empty($reports)) return [];
    $result = $reports[0];
    foreach (array_slice($reports, 1) as $report) {
        $result = mergeNestedArrays($result, $report);
    }
    return $result;
}

// 调用示例:合并今日和昨日报表
$combinedReport = mergeReports($reportToday, $reportYesterday);

// 合并多组报表示例
// $combinedReport = mergeReports($report1, $report2, $report3, ...);

var_dump($combinedReport);

函数说明

  • mergeNestedArrays:核心递归逻辑,遍历数组键值对,判断类型后分别处理嵌套数组合并、数值求和、非数值保留。
  • mergeReports:封装多数组合并流程,支持传入2到30组报表数组,依次合并得到最终结果。

内容的提问来源于stack exchange,提问作者Ryan H

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 23:15:44