我需要在数组中推送更多键及其值。如果我使用下面的代码,第一个密钥对被第二个密钥对替换。
供参考:
使用的代码:
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中构建此数组?任何一个帮助??
答案 0 :(得分:5)
使用
$projectData['projectsections'][$key] = ['name' => $name];
$projectData['projectsections'][$key]= ['id' => '1'];
您正在为$key
设置一个新数组。这不是你想要的。
这应该有效:
$projectData['projectsections'][$key] = ['name' => $name, 'id' => '1'];
答案 1 :(得分:5)
您需要添加整个数组:
$projectData['projectsections'][$key] = ['name' => $name, 'id' => '1'];
或使用键名添加:
$projectData['projectsections'][$key]['name'] = $name;
$projectData['projectsections'][$key]['id'] = '1';
答案 2 :(得分:3)
将其更改为:
foreach ($projectData['projectsections'] as $key => $name) {
$projectData['projectsections'][$key]['name'] = $name;
$projectData['projectsections'][$key]['id'] = '1';
}