编程语言
首页 > 编程语言> > php – 需要在关联数组中推送键和值吗?

php – 需要在关联数组中推送键和值吗?

作者:互联网

我需要在数组中推送更多键及其值.如果我使用下面的代码,第一个密钥对被第二个替换.

供你参考:

使用代码:

foreach ($projectData['projectsections'] as $key => $name) {
$projectData['projectsections'][$key] = ['name' => $name];
$projectData['projectsections'][$key]= ['id' => '1'];
}

目前的结果:

'projectsections' => [
    (int) 0 => [
        'id' => '1'
    ],
    (int) 1 => [
        'id' => '1'
    ]
],

预期:

'projectsections' => [
    (int) 0 => [
        'name' => 'test1',
        'id' => '1'
    ],
    (int) 1 => [
        'name' => 'test2',
        'id' => '1'
    ]
],

如何在PHP中构建此数组?有人帮忙吗?

解决方法:

您需要添加整个数组:

$projectData['projectsections'][$key] = ['name' => $name, 'id' => '1'];

或者使用键名添加:

$projectData['projectsections'][$key]['name'] = $name;
$projectData['projectsections'][$key]['id'] = '1';

标签:php,arrays,associative
来源: https://codeday.me/bug/20190714/1458115.html