我通过 PDO 返回一个关联数组,其结构如下:
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
)
)
这可能吗?
谢谢/汤姆
你必须像下面这样:
$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
}
或者你也可以这样做:
$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
}