29 tháng 11 2006

PHP - Deep Copy

An improvement to the array_deep_copy function I posted ages ago which takes a 'snapshot' of an array, making copies of all actual values referenced... Now it is possible to prevent it traversing the tree forever when an array references itself. You can set the default $maxdepth to anything you like, you should never call this function with the $depth specified!
/* Make a complete deep copy of an array replacing
references with deep copies until a certain depth is reached
($maxdepth) whereupon references are copied as-is... */
function array_deep_copy (&$array, &$copy, $maxdepth=50, $depth=0) {
if(
$depth > $maxdepth) { $copy = $array; return; }
if(!
is_array($copy)) $copy = array();
foreach(
$array as $k => &$v) {
if(
is_array($v)) { array_deep_copy($v,$copy[$k],$maxdepth,++$depth);
} else {
$copy[$k] = $v;
}
}
}

# call it like this:

array_deep_copy($array_to_be_copied,$deep_copy_of_array,$maxdepth);
?>
Hope someone finds it useful!

Không có nhận xét nào: