开发者

How to create differenet instances of an object from a single class while iterating an array in php?

开发者 https://www.devze.com 2023-03-25 22:10 出处:网络
I have this array for doctrine to process many to many form and save it to db but my code is not working because only one instance of object is created and then rewritten when iterating through the ar

I have this array for doctrine to process many to many form and save it to db but my code is not working because only one instance of object is created and then rewritten when iterating through the array:

$i = '1';
foreach ($myarray as $key => $value) {
  foreach ($value as $key2 => $value2) {
    $addressObject = new \Entities\Clientaddress();
    foreach ($value2 as $key3 => $value3) {
      $addressObject ->$key3 = $value3;
      $account->getAddresses()->add($addressObject);
      $this->em->persist($addressObje开发者_高级运维ct );
      $i = $i + '1';
}}}

If my approach is wrong what is the correct approach to create an object without defining it explicitly?


You could just create a new one in the loop, seems 'cleaner' / more legible to the next coder, unless the constructor is quite a heavy one that doesn't need repeating. That would get my vote. If you want copies of objects, use clone:

  ....
  foreach ($value2 as $key3 => $value3) {
      $curAdress = clone $addressObject;
      $curAdress->$key3 = $value3;
      $account->getAddresses()->add($curAdress);
      $this->em->persist($curAdress);


create an array of those objects:

    $addressObject = array();
    $i = '1';
    foreach ($myarray as $key => $value) {
         foreach ($value as $key2 => $value2) {

             // create array of objects here
             $addressObject[$key2] = new \Entities\Clientaddress();

             foreach ($value2 as $key3 => $value3) {
                 $addressObject[$key2] ->$key3 = $value3;
                 $account->getAddresses()->add($addressObject[$key2]);
                 $this->em->persist($addressObject[$key2] );
                 $i = $i + '1';
             }
         }
    }


Create your object in the final nested loop.

$i = '1';

 foreach ($myarray as $key => $value)
{ 
 foreach ($value as $key2 => $value2)
 { 
  foreach ($value2 as $key3 => $value3)
 {
   //create your object here
   $addressObject = new \Entities\Clientaddress();  
   $addressObject ->$key3 = $value3; 
   $account->getAddresses()->add($addressObject); 
   $this->em->persist($addressObject ); 
   $i = $i + '1'; 
  }
 }
} 
0

精彩评论

暂无评论...
验证码 换一张
取 消