1

I would like to loop through the contents of a query object update certain values and return the object.

function clearAllIds($queryObject)
{ 
   foreach($queryObject->result() as $row)
 {
  $row->id = 0;
 }
return $queryObject
}

In this example I would like to zero out all of the ID values. How can I accomplish this within the foreach loop?

Please excuse the formatting.

3 Answers 3

5

This entirely depends on what the class of your query object is, and whether or not you'll be able to Pass by reference.

Assuming your $queryObject->result() can be delivered in a write-context, you could preface the $row with an ampersand to pass it by reference, like so:

foreach($queryObject->result() as &$row)
{
    $row->id = 0;
}
Sign up to request clarification or add additional context in comments.

Comments

0
function clearAllIds($queryObject)
{ 
   foreach($queryObject->result() as &$row)
   {
     $row->id = 0;
   }
   return $queryObject
}

Use the & operator to get $row as a reference.

Edit: This will work if $queryObject is an array. You should probably do

$data = $queryObject->result();
foreach($data as &$row) { ... }
return $data;

Comments

0
function trim_spaces($object)
        {       
            foreach (get_object_vars($object) as $property=> $value) 
                {
                    $object->$property=trim($value);
                }
         }

//no need to return object as they are passed by reference by default

1 Comment

Add a description to your ans as well, explaining it.

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.