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

PHP动态将多维数组插入另一多维数组的实现方案求助

PHP多维数组对应合并实现

要实现将第二个数组的每个元素对应插入第一个数组的Sweden子数组中,可通过遍历+数组合并的方式完成,以下是具体解决方案:

原始数组定义

先明确两个原始数组的PHP代码定义:

$array1 = [
    '2019' => [
        'Sweden' => [
            'population' => '1000'
        ]
    ],
    '2020' => [
        'Sweden' => [
            'population' => '1500'
        ]
    ]
];

$array2 = [
    [
        'Facebook' => ['accounts' => '340'],
        'Instagram' => ['accounts' => '750'],
        'Linkedin' => ['accounts' => '560'],
    ],
    [
        'Facebook' => ['accounts' => '290'],
        'Instagram' => ['accounts' => '800'],
        'Linkedin' => ['accounts' => '378'],
    ]
];

核心处理代码

遍历第一个数组,通过引用直接修改原数组,同时用计数器对应第二个数组的索引元素,使用array_merge将元素合并到目标子数组:

$index = 0;
foreach ($array1 as &$yearData) {
    $yearData['Sweden'] = array_merge($yearData['Sweden'], $array2[$index]);
    $index++;
}
// 释放引用,避免后续操作污染数组
unset($yearData);

健壮性优化(可选)

如果两个数组的元素数量可能不一致,建议添加边界判断,避免索引越界报错:

$index = 0;
$array2Length = count($array2);
foreach ($array1 as &$yearData) {
    if ($index < $array2Length) {
        $yearData['Sweden'] = array_merge($yearData['Sweden'], $array2[$index]);
    }
    $index++;
}
unset($yearData);

最终结果

执行上述代码后,$array1将变为期望的结构:

[
    '2019' => [
        'Sweden' => [
            'population' => '1000',
            'Facebook' => ['accounts' => '340'],
            'Instagram' => ['accounts' => '750'],
            'Linkedin' => ['accounts' => '560'],
        ]
    ],
    '2020' => [
        'Sweden' => [
            'population' => '1500',
            'Facebook' => ['accounts' => '290'],
            'Instagram' => ['accounts' => '800'],
            'Linkedin' => ['accounts' => '378'],
        ]
    ]
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 04:25:42