Search code examples
phparraysassociative

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


Solution

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