0

I'm trying to dynamically add items to an array based on the number given by a user. I reference a template that has an array of object data inside of it. I get that Object by its SectionName and then through the for loop I'm trying to dynamically Change the SectionId and SectionName but Im getting the same one in there no mater what number is entered above 1.

$decodedTemplateArray = array();
// decoded json template to array
$decodedTemplateArray = json_decode($templateJsonData[0]->UnitTemplateForm);
// find location of bedroom section in array
$bedroomSectionLocation = array_search("Bedroom", array_column($decodedTemplateArray, 'SectionName'));
// set bedroom section to be created
$bedroomSectionObj = $decodedTemplateArray[$bedroomSectionLocation];
// remove bedroom from Template
unset($decodedTemplateArray[$bedroomSectionLocation]);
// insert 3/4/5
for ($x = 1; $x <= $bedroomCount; $x++) {
  $secGuid = self::generateGuid();
  $bedroomSectionObj->SectionId = $secGuid;
  $bedroomSectionObj->SectionName = "Bedroom " . $x;
  array_push( $decodedTemplateArray, $bedroomSectionObj);
}

Array Result:

7: {SectionId: "915E3E49-619F-190E-BFD4-7892871B1530", SectionName: "Bedroom 2", SectionDisplaySequence: 3, SectionItems: Array(9)}
8: {SectionId: "915E3E49-619F-190E-BFD4-7892871B1530", SectionName: "Bedroom 2", SectionDisplaySequence: 3, SectionItems: Array(9)}

1 Answers1

0

Objects are passed by reference by default (see this question for details, since this term "by reference" is not completely true). And you always pass the same Object(-identifier) to array_push(). A workaround is to clone this object:

<?php
// mocking some data and pre-setting vars
$bedroomSectionObj = new stdClass();
$bedroomSectionObj->default = "test";
$decodedTemplateArray = [];
$bedroomCount = 2;


for ($x = 1; $x <= $bedroomCount; $x++) {
  #$secGuid = self::generateGuid();
  // here I clone the original Object and use the clone instead:
  $clone = clone $bedroomSectionObj;
  #$clone->SectionId = $secGuid;
  $clone->SectionName = "Bedroom " . $x;
  array_push( $decodedTemplateArray, $clone);
}

var_dump($decodedTemplateArray);

// OUTPUT:
array(2) {
  [0]=>
  object(stdClass)#2 (2) {
    ["default"]=>
    string(4) "test"
    ["SectionName"]=>
    string(9) "Bedroom 1"
  }
  [1]=>
  object(stdClass)#3 (2) {
    ["default"]=>
    string(4) "test"
    ["SectionName"]=>
    string(9) "Bedroom 2"
  }
}
Jeff
  • 6,895
  • 1
  • 15
  • 33
  • 1
    Jeff. That is exactly what I needed. Thank you for the PHP reference as well it helped me understand it a bit more. – user3450960 Jan 13 '19 at 02:42