需要将键和值放入关联数组中吗?

3
我需要将更多的键和值推送到数组中。如果我使用下面的代码,第一个键值对会被第二个替换。
供您参考:
代码如下:
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中构建这个数组?有人可以帮忙吗?


2
你正在用第三行覆盖你的数组,只需将第2行和第3行合并即可。 - ctwheels
3个回答

5

With

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

你正在为$key设置一个新的数组。这不是你想要的。

这样做应该可以:

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

5
你需要添加整个数组:
$projectData['projectsections'][$key] = ['name' => $name, 'id' => '1'];

或者使用键名添加:

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

3
将其改为:
foreach ($projectData['projectsections'] as $key => $name) {
  $projectData['projectsections'][$key]['name'] = $name;
  $projectData['projectsections'][$key]['id'] = '1';
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接