0

I want to add a new index to my array of objects and be able to loop and retrieve that new index added.

Currently my array of objects is the following:

Array ([0] => 
            stdClass Object ([id] => 4 [date] => 2014-09-08 10:18:10 [status] => 1)
      )

So, to loop it I just do:

foreach($content as $item){
   echo $item->id;
}

But, for some reasons, I need to push a new element to my array:

$item  = $data['content']; // $data holds the content above
$clone = array();
foreach($item as $row){

  if($row->status == 1){

     array_push($clone, $row, array("delete" => TRUE));
  }else{

     array_push($clone, $row, array("delete" => FALSE));
  }
}
$item = $clone;

And the output is this:

Array ( [0] => 
            stdClass Object ([id] => 4 [date] => 2014-09-08 10:18:10 [status] => 1) [1] => Array ( [delete] => 1)
      )

But instead I would like something like

 Array ( [0] => 
                stdClass Object ([id] => 4 [date] => 2014-09-08 10:18:10 [status] => 1 [delete] => 1) 
          )

I also tried:

$item[] = (object) array("delete" => FALSE);

But the problem persists.

2 Answers 2

2

this is enough:

foreach($item as $row) {
    $row->delete = ($row->status == 1);
}
Sign up to request clarification or add additional context in comments.

4 Comments

it's wrong it won't modify the array because of no refference and it won't put delete property to object when status is not equal to 1.
@Robert no need to use reference & for objects
@Robert ups sorry I missed the fact OP want to set "false" as well
yes you're right my bad with refference :) now after you change assigment it's okay.
1

It's object so set variable as object variable

foreach($item as $row)
     $row->delete = $row->status ? true : false;

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.