phparraysmultidimensional-arrayappend

Add an element to each row of an array of associative arrays


I'm returning an associative array via PDO that has the structure:

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
        )
)

I want to add a key-value pair to the "inner" array, but all my attempts of trying to use posted solutions to the generic issue of adding to an associative array:

$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
    }
}

...result in the pair being added to the "outer" array e.g.

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
        )
)

Is this possible?


Solution

  • You have to it like below:

    $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
    }
    

    Or you can do like this also:

    $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
    }