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

如何在PHP中从源数组向目标数组填充对应水果组合数值?

解决方案

你可以通过嵌套循环遍历源数组,将对应位置的数值直接覆盖到目标数组的对应键位上,代码实现如下:

// 源数组(包含部分水果组合的数值)
$source = [
    'Apple' => [
        'Pineaple' => 4,
        'Strawberry' => 1
    ],
    'Watermelon' => [
        'Peach' => 3
    ]
];

// 目标数组(预设完整结构,初始值为0)
$target = [
    'Apple' => [
        'Pineaple' => 0,
        'Strawberry' => 0,
        'Watermelon' => 0,
        'Peach' => 0
    ],
    'Watermelon' => [
        'Pineaple' => 0,
        'Strawberry' => 0,
        'Watermelon' => 0,
        'Peach' => 0
    ]
];

// 执行填充操作
foreach ($source as $mainFruit => $subCombos) {
    foreach ($subCombos as $subFruit => $value) {
        $target[$mainFruit][$subFruit] = $value;
    }
}

// 查看结果
print_r($target);

说明

因为目标数组已经预先定义了所有需要的键结构,所以无需额外判断键是否存在,直接通过两层循环遍历源数组的键值对,将数值赋值到目标数组对应位置即可,未被赋值的位置会保留初始的0值,最终得到你需要的结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 07:45:38