Leena
Leena

Reputation: 61

Need to push the key and value inside associative Array?

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??

Upvotes: 3

Views: 85

Answers (3)

colburton
colburton

Reputation: 4715

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'];

Upvotes: 5

AbraCadaver
AbraCadaver

Reputation: 78994

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';

Upvotes: 5

Derek
Derek

Reputation: 3016

Change it to :

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

Upvotes: 3

Related Questions