Do I need to push key and value inside an associative array?

I need to push more of a key and its value inside an array. If I use below code the first key pair is replaced with the second one.

For reference:

Used code:

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

+3


source to share


3 answers


You need to either add the entire array:

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

      



Or add the name of the key:

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

      

+5


source


FROM

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

      

you are setting a new array for this $key

. This is not what you want.



This should work:

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

      

+5


source


Change it to:

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

      

+3


source







All Articles