簡體   English   中英

PHP防止foreach循環覆蓋對象

[英]PHP prevent foreach loop from overwriting object

這是我第四次嘗試寫這個問題,所以請耐心等待。

我有一個來自數據庫查詢的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以比較循環userIdgifts對陣列userId存儲在會話cookie。

從這些循環我創建了一系列用戶選擇的兒童和禮物。

問題是這會覆蓋我的主要對象而不是創建一個新對象。

循環:

$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); 它顯示已編輯的列表,而不是事件的完整列表。 有沒有辦法創建一個重復的對象並編輯它而不是編輯原始對象?

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

這不會深度復制$child的內容,但會使$tempChild$child指向相同的數據結構,這在這種情況下顯然是不可取的。

您應使用以下示例中的clone

$tempChild = clone $child;

嘗試

$tempEvents = clone $events;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM