3

I need to push the more key and its value inside the array. If I use below code first key pair replaced by 2nd one.

For your Reference:

Code Used:

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

Current result:

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

Expected:

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

How can I build this array in PHP?? Any one help??

Leena
  • 43
  • 1
  • 7

3 Answers3

5

With

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

you are setting a new Array for that $key. This is not what you want.

This should work:

$projectData['projectsections'][$key] = ['name' => $name, 'id' => '1'];
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
colburton
  • 4,685
  • 2
  • 26
  • 39
5

You need to either add the entire array:

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

Or add with the key name:

$projectData['projectsections'][$key]['name'] = $name;
$projectData['projectsections'][$key]['id'] = '1';
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
3

Change it to :

foreach ($projectData['projectsections'] as $key => $name) {
  $projectData['projectsections'][$key]['name'] = $name;
  $projectData['projectsections'][$key]['id'] = '1';
}
Derek
  • 2,927
  • 3
  • 20
  • 33