3

I am trying to add another key and value to the an array inside the foreach loop. I have the following array.

    array (size=2)
  0 => 
    object(stdClass)[27]
      public 'ID' => string '1' (length=1)
      public 'sectiontitle' => string 'Personal Information' (length=20)
      public 'field_format' => string 'vertical' (length=8)
      public 'status' => string '1' (length=1)

and the php code

       foreach ($query->result() as $row) {
            $data[] = $row;
         }
        var_dump($data);
        return $data;

i would like to add key [fields] and value string to it.

4
  • Why not you use foreach ($query->result() as $key=>$value) { Commented Jul 8, 2015 at 6:54
  • I did try that, it didn't work, could you give me an example please Commented Jul 8, 2015 at 6:55
  • possible duplicate of PHP push new key and value in existing object array Commented Jul 8, 2015 at 6:55
  • @Uchicha That is from out side of the foreach loop i am trying to add the new key value at the end of current loop Commented Jul 8, 2015 at 6:57

1 Answer 1

2

Try this

foreach ($query->result() as $row) {
                $row->newKey = $newValue;
                $data[] = $row;
             }
            var_dump($data);
            return $data;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.