我回來通過PDO的關聯數組具有以下結構的多維關聯數組(在PHP):添加到
Array
(
[0] => Array
(
[pesttopicID] => 42
[sPestName] => CMSM Trap Surveying and Pest Management
[quizID] => 609
[bTier1] => 1
[sDesc] => Workshop assessment
)
[1] => Array
(
[pesttopicID] => 34
[sPestName] => Trap Surveyor
[quizID] => 451
[bTier1] => 1
[sDesc] => Competency for CM OAP
)
)
欲一個鍵 - 值對添加到「內部」陣列,但我試圖用發佈的解決方案來增加關聯數組的一般問題的所有嘗試...
:
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$newkey='myNewKey';
$newval='myNewValue';
foreach($results as $row){
$results[][$newkey] = $newval;
foreach ($row as $key=>$value){
... some reporting stuff
}
}
...導致對被添加到「外」排列如
Array
(
[0] => Array <---- I want the new pair in this "inner" array
(
[pesttopicID] => 42
[sPestName] => CMSM Trap Surveying and Pest Management
[quizID] => 609
[bTier1] => 1
[sDesc] => Workshop assessment
)
[1] => Array <---- I want the new pair in this "inner" array
(
[pesttopicID] => 34
[sPestName] => Trap Surveyor
[quizID] => 451
[bTier1] => 1
[sDesc] => Competency for CM OAP
)
[2] => Array
(
[myNewKey] => myNewValue
)
)
這可能嗎?
感謝/湯姆
所以你要'[myNewKey] => myNewValue'添加到每個子陣? –
爲了您的將來refrence'$ results [] [$ newkey] = $ newval;''''''意味着在'$ results'的末尾創建一個新元素並添加一些內容。這就是爲什麼你有一些問題。 – IsThisJavascript
閱讀如何使用[方括號語法]訪問數組項目(http://php.net/manual/en/language.types.array.php#language.types.array.syntax.accessing)。 – axiac