Search code examples
phparraysobjectmultidimensional-array

Calculate and declare "total" property of an object while looping an objectArray


I have an array, lets call it $order that look like this

Array ( 
[0] => stdClass Object ( 
    [model] => Test Model Number 900 
    [quantity] => 100 
    [retail_per_unit] => 50.0000
) 
[1] => stdClass Object ( 
    [model] => model 2 
    [quantity] => 5 
    [retail_per_unit] => 100.0000
) 

then I foreach loop through $order to do some calculation and get another array, lets call it $total

so my $total array look like this

Array ( 
    [0] => 5000
    [1] => 500
)

Now I want to insert a key value pair back into the array so it becomes

Array ( 
[0] => stdClass Object ( 
    [model] => Test Model Number 900 
    [quantity] => 100 
    [retail_per_unit] => 50.0000
    [total] => 5000
) 
[1] => stdClass Object ( 
    [model] => model 2 
    [quantity] => 5 
    [retail_per_unit] => 100.0000 
    [total] => 500
) 

I tried $order['total'] = $total; and I get Indirect modification of overloaded property $order has no effect.

What is the right way to go about doing this?

The for loop method seems to be doing what I want, but I still get the indirect error. Here some additional information that might be related to it.

my $order array is actually

$template->order 

it gets the object array like this

$template->order = $someClass->someQuery($id);

and $template is calling a class

$template = new Template(dirname(__DIR__).'/templates/templatepage.php');

maybe $template->order changes the syntax somehow?


Solution

  • Why not just put the totals in as you go?

    foreach ($order as $x) {
        $x->total = $x->quantity * $x->retail_per_unit;
    }