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

如何通过函数向PHP关联数组中添加键值对?

如何在PHP关联数组创建时插入函数返回的键值对

这种需求完全可行,下面提供两种实现方式:

方法1:使用array_merge()合并数组

通过array_merge()将初始数组片段、函数返回的数组、后续数组片段合并,函数返回的键值对会被直接展开到主数组中:

$array = array_merge(
    [
        'key1' => [
            'attribute1' => 'value1',
            'attribute2' => 'value2',
            'attribute3' => 'value3',
        ]
    ],
    getArrayElements(),
    [
        'key2' => [
            'attribute1' => 'value1',
            'attribute2' => 'value2',
            'attribute3' => 'value3',
        ]
    ]
);

function getArrayElements()
{
    return [
        'additional_key_1'  => [
            'attribute1' => 'value1',
            'attribute2' => 'value2',
            'attribute3' => 'value3',
        ],
        'additional_key_2'  => [
            'attribute1' => 'value1',
            'attribute2' => 'value2',
            'attribute3' => 'value3',
        ],
    ];
}

方法2:PHP 7.4+ 使用数组展开语法...

PHP 7.4及以上版本支持用...语法直接展开数组,写法更简洁直观:

$array = [
    'key1' => [
        'attribute1' => 'value1',
        'attribute2' => 'value2',
        'attribute3' => 'value3',
    ],
    ...getArrayElements(),
    'key2' => [
        'attribute1' => 'value1',
        'attribute2' => 'value2',
        'attribute3' => 'value3',
    ]
];

function getArrayElements()
{
    return [
        'additional_key_1'  => [
            'attribute1' => 'value1',
            'attribute2' => 'value2',
            'attribute3' => 'value3',
        ],
        'additional_key_2'  => [
            'attribute1' => 'value1',
            'attribute2' => 'value2',
            'attribute3' => 'value3',
        ],
    ];
}

注意事项

如果函数返回的数组与主数组中的键名重复,后面的键值对会覆盖前面的(比如key1若和函数返回的某个键重复,合并后会保留后续的对应值)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 08:23:55