I am trying to perform a transformation/calculation on values in a returned SQL object, based on other values in the same row. I cannot find a good reference for this, perhaps I just don't know what I'm looking for; it seems most functions (e.g array_walk) are for applying the same transformation to all values in an entire array? I want to alter just certain values, conditionally.
Here is my simplified attempt; doesn't work, but I think shows what I'm trying to do:
//------CREATE OBJECT-------//
$sql2 = "select internalname, value, adjboolean, adjfactor
FROM superfilters WHERE id > '0'";
$filterobject = $DBLink->query($sql2);
//------MODIFY OBJECT------//
$input1 = 350;
$input2 = 175;
foreach ($filterobject as $row){
if ($row['adjboolean'] = 1) {
$row['value'] += ($row['value'] * ($input1 / $input2 - 1) * $row['adjfactor']);
}
}
After trying to modify, no errors are thrown, but there is no effect on my row value. I'd prefer to over-write, not create a duplicate array/object, but I could create new if necessary to perform the function.
Huge thanks for any help!
----EDIT---- Ok, so I have now learned that foreach actually works on a copy of my $filterobject, and I must reference in order to modify the actual result object. It seems the following should work
foreach ($filterobject as &$row){
However, I get the error "An iterator cannot be used with foreach by reference". So, now I'm working on that...
You need to add an
&
to let$row
be updated by reference, otherwise it will get overwritten each time you loop and won't persist outside of the foreach.Also, I assume your
adjboolean
check should be a comparison rather than an assignment? Use==
instead of=
.FYI,
array_walk()
will walk as well, you will just need touse
your external variables to allow them to be accessible inside the callback's scope:Examples here.