添加到多维关联数组(在 PHP 中)[重复]

问题描述 投票:0回答:1

我通过 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
        )
)

这可能吗?

谢谢/汤姆

php multidimensional-array
1个回答
3
投票

你必须像下面这样:

$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
}
© www.soinside.com 2019 - 2024. All rights reserved.