How to clone an array of objects in PHP?

后端 未结 15 738
鱼传尺愫
鱼传尺愫 2020-12-13 17:00

I have an array of objects. I know that objects get assigned by \"reference\" and arrays by \"value\". But when I assign the array, each element of the array is referencing

15条回答
  •  旧时难觅i
    2020-12-13 17:47

    You need to clone objects to avoid having references to the same object.

    function array_copy($arr) {
        $newArray = array();
        foreach($arr as $key => $value) {
            if(is_array($value)) $newArray[$key] = array_copy($value);
            else if(is_object($value)) $newArray[$key] = clone $value;
            else $newArray[$key] = $value;
        }
        return $newArray;
    }
    

提交回复
热议问题