2017-06-28 49 views
3

我需要將更多的鍵和它的值推入數組中。如果我使用下面的代碼第一個密鑰對替換爲第二個密鑰對。需要推關聯數組內的鍵和值?

,供大家參考:

代碼中使用:

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中構建這個數組?任何一個幫助?

+2

你重寫你的數組與你的第三條線,只是結合第2和第3行 – ctwheels

回答

5

您需要可以添加整個數組:

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

使用該密鑰名稱添加:

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

將其更改爲:

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

隨着

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

要設置爲$key一個新的陣列。這不是你想要的。

這應該工作:

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