2017-09-07 17 views
-1

我回來通過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 
     ) 
) 

這可能嗎?

感謝/湯姆

+0

所以你要'[myNewKey] => myNewValue'添加到每個子陣? –

+0

爲了您的將來refrence'$ results [] [$ newkey] = $ newval;''''''意味着在'$ results'的末尾創建一個新元素並添加一些內容。這就是爲什麼你有一些問題。 – IsThisJavascript

+0

閱讀如何使用[方括號語法]訪問數組項目(http://php.net/manual/en/language.types.array.php#language.types.array.syntax.accessing)。 – axiac

回答

1

你必須給它象下面這樣: -

$newkey='myNewKey'; 
$newval='myNewValue'; 
foreach($results as &$row){ //use reference variable 
    $row[$newkey] = $newval;// remove the second foreach if not necessary 
    //if second foreach is necessary then add it no problem 
} 

輸出: - https://eval.in/856983

或者你也可以做到這樣也: -

$newkey='myNewKey'; 
$newval='myNewValue'; 
foreach($results as $key=>$row){ //use key now 
    $results[$key][$newkey] = $newval;// remove the second foreach if not necessary 
    //if second foreach is necessary then add it no problem 
} 

輸出: - https://eval.in/856987

+1

謝謝。而且我現在也瞭解了&$ row結構 - 在我之前關於該主題的閱讀中,我沒有遇到過這種結構。乾杯/湯姆 – TomBaine

-4

嘗試

foreach($results as &$result) 
{ 
    $result[$key] = $value; 
} 

編輯:SRY我犯了一個錯誤

+0

不會工作,因爲在這種情況下, '$ row'是一個數組。你會將整個數組當作一個鍵而不是數組鍵 – IsThisJavascript

+0

你的更新後的代碼仍然不起作用,因爲在OP中,他沒有設置'$ row'作爲參考(關於我的意思,請參閱其他答案) 。 – IsThisJavascript