PHP参考数组的深层副本?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (29)

所以$ array是所有元素都是引用的数组。

我想将这个数组附加到另​​一个名为$ results的数组(在一个循环中),但由于它们是引用,所以PHP复制引用并且$ results充满了相同的元素。

到目前为止,最好的工作解决方案是:

$results[] = unserialize(serialize($array));

有一个更好的方法吗?

提问于
用户回答回答于
$original = 'foo';
$array_of_reference = array(&$original);

function myclone($value)
{
  return $value;
}

$array_by_myclone = array();
$array_by_myclone[] = array_map('myclone', $array_of_reference);

$array_by_assignment = array();
$array_by_assignment[] = $array_of_reference;

$original = 'bar';

var_dump($array_by_myclone[0][0]); // foo, values were cloned                                                                                                                                   
var_dump($array_by_assignment[0][0]); // bar, still a reference                     

lepidosteus@server:~$ php -v
PHP 5.5.1-1~dotdeb.1 (cli) (built: Aug  3 2013 22:19:30) 
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2013 Zend Technologies
    with Zend OPcache v7.0.2-dev, Copyright (c) 1999-2013, by Zend Technologies
lepidosteus@server:~$ php reference.php 1
myclone:   0.000010 seconds
serialize: 0.000012 seconds
lepidosteus@server:~$ php reference.php 1000000
myclone:   0.398540 seconds
serialize: 0.706631 seconds

使用的代码:

<?php
$iterations = 1000000;
if (isset($argv[1]) && is_numeric($argv[1])) {
  $iterations = max(1, (int)$argv[1]);
}

$items = array();
for ($i = 0; $i < $iterations; $i++) {
  $items[] = 'item number '.$i;
}

$array_of_refs = array();
foreach ($items as $k => $v) {
  $array_of_refs[] = &$items[$k];
}

function myclone($value)
{
  return $value;
}

$start = microtime(true);

$copy = array_map('myclone', $array_of_refs);

$time = microtime(true) - $start;

printf("%-10s %2.6f seconds\n", 'myclone:', $time);

$start = microtime(true);

$copy = unserialize(serialize($array_of_refs));

$time = microtime(true) - $start;

printf("%-10s %2.6f seconds\n", 'serialize:', $time);
用户回答回答于
$original = array('key'=>'foo');
$array_of_reference = array(&$original);
function myclone($value)
{
  return $value;
}
$array_by_myclone = array();
$array_by_myclone[] = array_map('myclone', $array_of_reference);

$array_by_assignment = array();
$array_by_assignment[] = $array_of_reference;

$original['key'] = 'bar';

var_dump($array_by_myclone[0][0]['key']); // bar, still a reference                                                                                                                                   
var_dump($array_by_assignment[0][0]['key']); // bar, still a reference   

扫码关注云+社区

领取腾讯云代金券