0

I am making an array of std objects in CodeIgniter

$result1 = $this->db->query($query1)->result();

and I am getting the following result

Result

Array
   (
    [0] => stdClass Object
      (
        [message_id] => 10
        [sender] => 22
        [receiver] => 24
        [message] => hello atif
        [sent_date] => 02-09-2016
        [sent_time] => 10:12:15am
    )  
 }

Now I want to add one more key after [sent_time] for example [anotherKey] => Another Value string how do I do that?

4
  • $result1[0]->anotherkey = 'string';? Commented Sep 5, 2016 at 10:49
  • the index is dynamic Commented Sep 5, 2016 at 10:50
  • i dont know how many indexes will come, they are depend on data Commented Sep 5, 2016 at 10:50
  • So do a foreach / while / loop of some kind... Commented Sep 5, 2016 at 10:52

2 Answers 2

1

You can try

foreach($result1 as $key=>$value)
{
    $result1[$key]->anotherKey = "Another value";

    $anotherKey = "anotherKey";
    //To apply dynamic value 
    $result1[$key]->$anotherKey = "Another value";
}
Sign up to request clarification or add additional context in comments.

1 Comment

@mohsinali you're welcome, great to see that works for you.
0

You can also extend object like this:

$obj = new stdClass;
$obj->anotherKey = "Another Value";

Or in loop:

foreach ($stdClass as $key => $value) {
    $stdClass[$key]->anotherKey = "Another Value";
}

2 Comments

how can i do in foreach dynamically can you please show how i do that
Check my answer for loop one.

Your Answer

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