是否有将 PHP 数组复制到另一个数组的函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1532618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a function to make a copy of a PHP array to another?
提问by vfclists
Is there a function to make a copy of a PHP array to another?
是否有将 PHP 数组复制到另一个数组的函数?
I have been burned a few times trying to copy PHP arrays. I want to copy an array defined inside an object to a global outside it.
我被烧了几次试图复制 PHP 数组。我想将对象内部定义的数组复制到它外部的全局对象中。
回答by troelskn
In PHP arrays are assigned by copy, while objects are assigned by reference. This means that:
在 PHP 中,数组是通过复制分配的,而对象是通过引用分配的。这意味着:
$a = array();
$b = $a;
$b['foo'] = 42;
var_dump($a);
Will yield:
将产生:
array(0) {
}
Whereas:
然而:
$a = new StdClass();
$b = $a;
$b->foo = 42;
var_dump($a);
Yields:
产量:
object(stdClass)#1 (1) {
["foo"]=>
int(42)
}
You could get confused by intricacies such as ArrayObject, which is an object that acts exactly like an array. Being an object however, it has reference semantics.
您可能会被诸如 之类的错综复杂的东西弄糊涂ArrayObject,它是一个完全类似于数组的对象。然而,作为一个对象,它具有引用语义。
Edit: @AndrewLarsson raises a point in the comments below. PHP has a special feature called "references". They are somewhat similar to pointers in languages like C/C++, but not quite the same. If your array contains references, then while the array itself is passed by copy, the references will still resolve to the original target. That's of course usually the desired behaviour, but I thought it was worth mentioning.
编辑:@AndrewLarsson 在下面的评论中提出了一个观点。PHP 有一个称为“引用”的特殊功能。它们有点类似于 C/C++ 等语言中的指针,但并不完全相同。如果您的数组包含引用,那么当数组本身通过副本传递时,引用仍将解析为原始目标。这当然通常是期望的行为,但我认为值得一提。
回答by slikts
PHP will copy the array by default. References in PHP have to be explicit.
PHP 默认会复制数组。PHP 中的引用必须是显式的。
$a = array(1,2);
$b = $a; // $b will be a different array
$c = &$a; // $c will be a reference to $a
回答by Andrew Larsson
If you have an array that contains objects, you need to make a copy of that array without touching its internal pointer, and you need all the objects to be cloned (so that you're not modifying the originals when you make changes to the copied array), use this.
如果您有一个包含对象的数组,则需要在不触及其内部指针的情况下制作该数组的副本,并且您需要克隆所有对象(以便在对复制的对象进行更改时不会修改原始对象)数组),使用这个。
The trick to not touching the array's internal pointer is to make sure you're working with a copy of the array, and not the original array (or a reference to it), so using a function parameter will get the job done (thus, this is a function that takes in an array).
不接触数组内部指针的技巧是确保您使用的是数组的副本,而不是原始数组(或对它的引用),因此使用函数参数将完成工作(因此,这是一个接受数组的函数)。
Note that you will still need to implement __clone()on your objects if you'd like their properties to also be cloned.
请注意,如果您希望对象的属性也被克隆,您仍然需要在对象上实现__clone()。
This function works for any type of array (including mixed type).
此函数适用于任何类型的数组(包括混合类型)。
function array_clone($array) {
return array_map(function($element) {
return ((is_array($element))
? array_clone($element)
: ((is_object($element))
? clone $element
: $element
)
);
}, $array);
}
回答by chaos
When you do
当你做
$array_x = $array_y;
PHP copies the array, so I'm not sure how you would have gotten burned. For your case,
PHP 复制数组,所以我不确定你会如何被烧毁。对于你的情况,
global $foo;
$foo = $obj->bar;
should work fine.
应该工作正常。
In order to get burned, I would think you'd either have to have been using references or expecting objects inside the arrays to be cloned.
为了被烧毁,我认为您要么必须一直使用引用,要么期望克隆数组内的对象。
回答by Kshitiz Saxena
array_merge()is a function in which you can copy one array to another in PHP.
array_merge()是一个可以在 PHP 中将一个数组复制到另一个数组的函数。
回答by Matthew Cornelisse
simple and makes deep copy breaking all links
简单,使深层复制打破所有链接
$new=unserialize(serialize($old));
回答by Putzi San
I like array_replace(or array_replace_recursive).
我喜欢array_replace(或array_replace_recursive)。
$cloned = array_replace([], $YOUR_ARRAY);
$cloned = array_replace([], $YOUR_ARRAY);
It works like Object.assignfrom JavaScript.
它的工作原理类似于Object.assignJavaScript。
$original = [ 'foo' => 'bar', 'fiz' => 'baz' ];
$cloned = array_replace([], $original);
$clonedWithReassignment = array_replace([], $original, ['foo' => 'changed']);
$clonedWithNewValues = array_replace([], $original, ['add' => 'new']);
$original['new'] = 'val';
will result in
会导致
// original:
{"foo":"bar","fiz":"baz","new":"val"}
// cloned:
{"foo":"bar","fiz":"baz"}
// cloned with reassignment:
{"foo":"changed","fiz":"baz"}
// cloned with new values:
{"foo":"bar","fiz":"baz","add":"new"}
回答by chrmcpn
If you have only basic types in your array you can do this:
如果你的数组中只有基本类型,你可以这样做:
$copy = json_decode( json_encode($array), true);
You won't need to update the references manually
I know it won't work for everyone, but it worked for me
你不需要手动更新参考
我知道它对每个人都不起作用,但它对我有用
回答by fyrye
Since this wasn't covered in any of the answers and is now available in PHP 5.3 (assumed Original Post was using 5.2).
由于这未包含在任何答案中,并且现在在 PHP 5.3 中可用(假设原始帖子使用的是 5.2)。
In order to maintain an array structure and change its values I prefer to use array_replaceor array_replace_recursivedepending on my use case.
为了维护数组结构并更改其值,我更喜欢使用array_replace或array_replace_recursive取决于我的用例。
http://php.net/manual/en/function.array-replace.php
http://php.net/manual/en/function.array-replace.php
Here is an example using array_replaceand array_replace_recursivedemonstrating it being able to maintain the indexed order and capable of removing a reference.
这是一个使用array_replace和array_replace_recursive演示它能够维护索引顺序并能够删除引用的示例。
The code below is written using the short array syntax available since PHP 5.4 which replaces array()with [].
http://php.net/manual/en/language.types.array.php
下面的代码是使用自 PHP 5.4 起可用的短数组语法编写的,它替换array()为[].
http://php.net/manual/en/language.types.array.php
Works on either offset indexed and name indexed arrays
适用于偏移索引和名称索引数组
$o1 = new stdClass;
$a = 'd';
//This is the base array or the initial structure
$o1->ar1 = ['a', 'b', ['ca', 'cb']];
$o1->ar1[3] = & $a; //set 3rd offset to reference $a
//direct copy (not passed by reference)
$o1->ar2 = $o1->ar1; //alternatively array_replace($o1->ar1, []);
$o1->ar1[0] = 'z'; //set offset 0 of ar1 = z do not change ar2
$o1->ar1[3] = 'e'; //$a = e (changes value of 3rd offset to e in ar1 and ar2)
//copy and remove reference to 3rd offset of ar1 and change 2nd offset to a new array
$o1->ar3 = array_replace($o1->ar1, [2 => ['aa'], 3 => 'd']);
//maintain original array of the 2nd offset in ar1 and change the value at offset 0
//also remove reference of the 2nd offset
//note: offset 3 and 2 are transposed
$o1->ar4 = array_replace_recursive($o1->ar1, [3 => 'f', 2 => ['bb']]);
var_dump($o1);
Output:
输出:
["ar1"]=>
array(4) {
[0]=>
string(1) "z"
[1]=>
string(1) "b"
[2]=>
array(2) {
[0]=>
string(2) "ca"
[1]=>
string(2) "cb"
}
[3]=>
&string(1) "e"
}
["ar2"]=>
array(4) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
array(2) {
[0]=>
string(2) "ca"
[1]=>
string(2) "cb"
}
[3]=>
&string(1) "e"
}
["ar3"]=>
array(4) {
[0]=>
string(1) "z"
[1]=>
string(1) "b"
[2]=>
array(1) {
[0]=>
string(2) "aa"
}
[3]=>
string(1) "d"
}
["ar4"]=>
array(4) {
[0]=>
string(1) "z"
[1]=>
string(1) "b"
[2]=>
array(2) {
[0]=>
string(2) "bb"
[1]=>
string(2) "cb"
}
[3]=>
string(1) "f"
}
回答by bestprogrammerintheworld
I know this as long time ago, but this worked for me..
我很久以前就知道这一点,但这对我有用..
$copied_array = array_slice($original_array,0,count($original_array));

