需要将键和值推送到关联数组中吗?
Need to push the key and value inside associative Array?
我需要将 more 键及其值压入数组中。如果我使用下面的代码将第一个密钥对替换为第二个密钥对。
供您参考:
使用代码:
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 中构建这个数组??有人帮忙吗??
将其更改为:
foreach ($projectData['projectsections'] as $key => $name) {
$projectData['projectsections'][$key]['name'] = $name;
$projectData['projectsections'][$key]['id'] = '1';
}
有
$projectData['projectsections'][$key] = ['name' => $name];
$projectData['projectsections'][$key]= ['id' => '1'];
您正在为 $key
设置一个新数组。这不是你想要的。
这应该有效:
$projectData['projectsections'][$key] = ['name' => $name, 'id' => '1'];
您需要添加整个数组:
$projectData['projectsections'][$key] = ['name' => $name, 'id' => '1'];
或添加键名:
$projectData['projectsections'][$key]['name'] = $name;
$projectData['projectsections'][$key]['id'] = '1';
我需要将 more 键及其值压入数组中。如果我使用下面的代码将第一个密钥对替换为第二个密钥对。
供您参考:
使用代码:
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 中构建这个数组??有人帮忙吗??
将其更改为:
foreach ($projectData['projectsections'] as $key => $name) {
$projectData['projectsections'][$key]['name'] = $name;
$projectData['projectsections'][$key]['id'] = '1';
}
有
$projectData['projectsections'][$key] = ['name' => $name];
$projectData['projectsections'][$key]= ['id' => '1'];
您正在为 $key
设置一个新数组。这不是你想要的。
这应该有效:
$projectData['projectsections'][$key] = ['name' => $name, 'id' => '1'];
您需要添加整个数组:
$projectData['projectsections'][$key] = ['name' => $name, 'id' => '1'];
或添加键名:
$projectData['projectsections'][$key]['name'] = $name;
$projectData['projectsections'][$key]['id'] = '1';