0

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?

3
  • so you want [myNewKey] => myNewValue added to each sub-array? Commented Sep 7, 2017 at 9:14
  • For your future refrence $results[][$newkey] = $newval; the [] means create a new element on the end of $results and add something to it. That's why you had some issues. Commented Sep 7, 2017 at 9:16
  • Read how to access array items using the square brackets syntax. Commented Sep 7, 2017 at 9:25

1 Answer 1

3

You have to do 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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. And I've also now learnt about the &$row construct - I'd not encountered that in my previous reading around the topic. Cheers/Tom

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.