简体   繁体   中英

PHP: For loop to add object to array is not changing variables at each count. It is duplicating the same object in the array

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)}

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"
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM