如何改变$数组2值,而不参照$ ARRAY1? [英] How to changing value in $array2 without referring $array1?
问题描述
考虑下面的PHP code段。
$ ARRAY1 =阵列(1,20);
$ X =安培; $数组1 [1];
$数组2 = $数组1;
$数组2 [1] = 22;
的print_r($数组1 [1]); //输出为22
在这里, $数组2
未引用到 $数组1
,但如何在<$ C $改变价值C> $数组2 $数组1 ?
如果你想 $数组2
是 $数组1 的参考code>那么你做同样的事情与
$ X
。
$数组2 =&放大器; $数组1;
现在任何你在改变任何 $数组1
或 $数组2
是在两个数组可见,因为 $数组2
仅仅是一个参考 $数组1
。
更新
想着它,你可能会看到的是改变价值的方式,但仍然有数组的完整副本。这是可行的与对象
$ OBJ =新stdClass的();
$ ARRAY1 =阵列(1,20);
$数组1 [1] = $ OBJ;
$数组1 [1] - &GT;彩色= 22;$数组2 = $数组1;
$数组2 [1] - &GT;彩色= 33;回声$数组1 [1] - &GT;颜色; //输出33
这是因为对象总是以引用复制,而数字和字符串原样复制。
Consider the following PHP code segment.
$array1 = array(1,20);
$x = &$array1[1];
$array2 = $array1;
$array2[1] = 22;
print_r($array1[1]); // Output is 22
Here, $array2
is not referencing to $array1
, but how to change value in $array2
by changing value of $array1
?
If you want $array2
to be a reference of $array1
then you do the same thing as with $x
.
$array2 = &$array1;
Now anything you change in either $array1
or $array2
is visible in both arrays since $array2
is just a reference to $array1
.
Update
Thinking about it, what you may be looking at is a way to change a value, but still have a full copy of the arrays. This is doable with an object.
$obj = new stdClass();
$array1 = array(1, 20);
$array1[1] = $obj;
$array1[1]->color = 22;
$array2 = $array1;
$array2[1]->color = 33;
echo $array1[1]->color; // prints 33
This is because objects are always copied by reference, whereas numbers and strings are copied as is.
这篇关于如何改变$数组2值,而不参照$ ARRAY1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!