[英]PHP prevent foreach loop from overwriting object
This is the fourth time I've tried writing this question, so please bear with me. 这是我第四次尝试写这个问题,所以请耐心等待。
I have a PHP object that comes from a DB Query which pulls back the following data: 我有一个来自数据库查询的PHP对象,它返回以下数据:
[1] => stdClass Object
(
[eventId] => 11
[eventName] => Second Event
[...]
[eventChildren] => Array
(
[0] => stdClass Object
(
[childId] => 8
[childName] => Jane Doe
[...]
[gifts] => Array
(
[0] => stdClass Object
(
[giftId] => 73
[giftName] => My two front teeth
[childId] => 8
[userId] => 1
[eventId] => 11
)
[1] => stdClass Object
(
[giftId] => 74
[giftName] => Wasps
[childId] => 8
[userId] => 1
[eventId] => 11
)
)
)
)
)
)
I'm then running a massive series of foreach
loops in order to compare the userId
from the gifts
array against the userId
stored in the session cookie. 我然后运行一个庞大的一系列
foreach
以比较循环userId
从gifts
对阵列userId
存储在会话cookie。
From these loops I'm creating an array of children and gifts that the user has selected. 从这些循环我创建了一系列用户选择的儿童和礼物。
The problem is this overwrites my main object rather than creating a new one. 问题是这会覆盖我的主要对象而不是创建一个新对象。
The Loops: 循环:
$user = $this->session->userdata('user');
$tempEvents = $events;
$userSelection = array();
$flag = FALSE;
foreach ( $tempEvents as $i => $event )
{
if ( $i == 0 )
{
foreach ( $event->eventChildren as $child )
{
$userGift = array();
foreach ( $child->gifts as $gift )
{
if ( $gift->userId == $user['userId'] )
{
array_push($userGift, $gift);
$flag = TRUE;
}
}
$tempChild = $child;
$tempChild->gifts = $userGift;
if ( $flag )
{
array_push($userSelection, $tempChild);
$flag = FALSE;
}
}
}
}
If I print_r($events);
如果我
print_r($events);
it displays the edited list rather than it's full list of events. 它显示已编辑的列表,而不是事件的完整列表。 Is there a way to create a duplicate object and edit that rather than editing the original object?
有没有办法创建一个重复的对象并编辑它而不是编辑原始对象?
The reason for the "overwriting" is $tempChild = $child;
“覆盖”的原因是
$tempChild = $child;
. 。
That will not deep copy the contents of $child
but make both $tempChild
and $child
point towards the same data structure, which obviously isn't desirable in this case. 这不会深度复制
$child
的内容,但会使$tempChild
和$child
指向相同的数据结构,这在这种情况下显然是不可取的。
You should use clone
as in the below example. 您应使用以下示例中的
clone
。
$tempChild = clone $child;
尝试
$tempEvents = clone $events;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.