如何在 PHP 中迭代数组时从单个类创建对象的不同实例?
我有这个数组用于处理多对多形式并将其保存到数据库,但我的代码不起作用,因为只创建了一个对象实例,然后在迭代数组时重写:
$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($addressObject );
$i = $i + '1';
}}}
如果我的方法是错误的,那么正确的方法是什么创建一个对象而不显式定义它?
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($addressObject );
$i = $i + '1';
}}}
If my approach is wrong what is the correct approach to create an object without defining it explicitly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在循环中创建一个新的构造函数,这对于下一个编码器来说似乎“更干净”/更清晰,除非构造函数非常繁重,不需要重复。那会得到我的投票。如果您想要对象的副本,请使用
clone
: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
:创建这些对象的数组:
create an array of those objects:
在最后的嵌套循环中创建对象。
Create your object in the final nested loop.