Created
November 28, 2014 09:35
-
-
Save boekkooi/f83cc79303e936384ea2 to your computer and use it in GitHub Desktop.
Deep copy Array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function arrayCopy(array $array) | |
{ | |
$hashList = array(); | |
$iterator = new \RecursiveIteratorIterator( | |
new \RecursiveArrayIterator($array), | |
\RecursiveIteratorIterator::SELF_FIRST | |
); | |
$iterator->rewind(); | |
$prevDepth = 0; | |
$current = array(); | |
$parents = array(&$current); | |
foreach ($iterator as $k => $v) { | |
if ($iterator->getDepth() < $prevDepth) { | |
for ($i = ($prevDepth - $iterator->getDepth()); $i > 0; $i--) { | |
array_pop($parents); | |
} | |
$current = &$parents[count($parents)-1]; | |
} | |
if (is_array($v)) { | |
$current[$k] = array(); | |
array_push($parents, $current[$k]); | |
$current =& $current[$k]; | |
} elseif (is_object($v)) { | |
if (!isset($hashList[spl_object_hash($v)])) { | |
$hashList[spl_object_hash($v)] = clone $v; | |
} | |
$current[$k] = $hashList[spl_object_hash($v)]; | |
} else { | |
$current[$k] = $v; | |
} | |
$prevDepth = $iterator->getDepth(); | |
} | |
$rtn = $parents[0]; | |
unset($current, $parents, $hashList); | |
return $rtn; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment