PHP阻止foreach循环覆盖对象

时间:2011-12-17 04:54:39

标签: php codeigniter foreach

这是我第四次尝试写这个问题,所以请耐心等待。

我有一个来自数据库查询的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
                                    )

                            )

                    )

            )

    )
)

然后我运行了大量的foreach循环,以便将userId数组中的gifts与会话Cookie中存储的userId进行比较。< / p>

从这些循环中,我创建了一个用户选择的子项和礼物数组。

问题是这会覆盖我的主要对象而不是创建一个新对象。

循环:

$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;
            }
        }
    }
}

如果我print_r($events);它显示已编辑的列表而不是它的完整事件列表。有没有办法创建一个重复的对象并编辑它而不是编辑原始对象?

2 个答案:

答案 0 :(得分:3)

“覆盖”的原因是$tempChild = $child;

这不会深度复制$child的内容,但会使$tempChild$child指向相同的数据结构,在这种情况下显然不可取。

您应该使用clone,如下例所示。

$tempChild = clone $child;

答案 1 :(得分:0)

尝试

$tempEvents = clone $events;