There is such a construction

$params = array ("Id"=>"{$deal_id}", "program"=>"2","Positions"=>array(array("OfferId"=>"89", "Count"=> "$total_area"), array("OfferId"=>"124", "Count"=> "$total_reika"), array("OfferId"=>"125", "Count"=> "$total_lightnings"))); $Price = new stdClass(); $Price->Value = 100; $params[Positions][0][Price] = $Price; $Price->Value = 200; $params[Positions][1][Price] = $Price; $Price->Value = 300; $params[Positions][2][Price] = $Price; 

Here is what print_r prints ($ params)

 Array ( [Id] => 531 [program] => 2 [Positions] => Array ( [0] => Array ( [OfferId] => 89 [Count] => 20 [Price] => stdClass Object ( [Value] => 300 ) ) [1] => Array ( [OfferId] => 124 [Count] => 1 [Price] => stdClass Object ( [Value] => 300 ) ) [2] => Array ( [OfferId] => 125 [Count] => 1 [Price] => stdClass Object ( [Value] => 300 ) ) ) ) 

Why is the value of Price-> Value for all positions equal to 300?

    2 answers 2

    Because the pointer to the once created Price object is placed in the array, and then the Value field is successively changed for this object.

    To prevent this from happening, you need to create a new object each time or clone the previous one.

     $Price = new stdClass(); $Price->Value = 100; $params['Positions'][0]['Price'] = clone $Price; $Price->Value = 200; $params['Positions'][1]['Price'] = clone $Price; 

    Read more in the documentation.

    PS String names of array indices are strongly recommended to be written in quotes

    Why is $ foo [bar] wrong?
    Always quote the string literal in the index of an associative array. For example, write $foo['bar'] , not $foo[bar] . But why? Often in the old scripts you can find the following syntax:

     <?php $foo[bar] = 'враг'; echo $foo[bar]; // и т.д. ?> 

    This is incorrect, although it works. The reason is that this code contains an undefined constant ( bar ), not a string ( 'bar' - pay attention to the quotes). This works because PHP automatically converts the "bare line" (not a quoted string that does not match any of the known characters of the language) into a string with the value of this "bare line". For example, if a constant named bar not defined, then PHP will replace bar with the string 'bar' and use it.

      All clear. All Positions in the array refer to the same object. Fixed by adding $ Price = new stdClass () before each value assignment