我有以下代码:
$data['x'] = $this->x->getResults();
$data['y'] = $data['x'];
//some code here to modify $data['y']
//this causes (undesirably) $data['x] to be modified as well
我想因为 $data 的所有元素本身都是引用,修改 $data['y'] 也会修改 $data['x']..这不是我想要的。我希望 $data['x'] 保持不变。有什么方法可以取消对此处元素的引用,以便我可以按值复制元素?
谢谢。
更新:$this->x->getResults();返回一个对象数组。所以我可以做类似的事情: $data['x'][0]->date_create ...
更新: 我最近尝试克隆阵列看起来像这样:
$data['x'] = $this->x->getResults();
$data['y'] = $data['y'];
foreach($data['x'] as $key=>$row) {
$data['y'][$key]->some_attr = clone $row->some_attr;
}
我离这里很远吗?我不断收到“在非对象上调用的 __clone 方法”错误。从阅读响应来看,我最好的选择似乎是遍历每个元素并克隆它(这就是我试图用该代码做的......)。
更新:刚刚解决了它!:在 foreach 循环中,我只需要将行更改为:
$data['y'][$key] = clone $row;
而且有效!感谢大家的帮助。
最佳答案
您可以利用 PHP 将取消引用函数调用结果这一事实。
这是我编写的一些示例代码:
$x = 'x';
$y = 'y';
$arr = array(&$x,&$y);
print_r($arr);
echo "<br/>";
$arr2 = $arr;
$arr2[0] = 'zzz';
print_r($arr);
print_r($arr2);
echo "<br/>";
$arr2 = array_flip(array_flip($arr));
$arr2[0] = '123';
print_r($arr);
print_r($arr2);
结果是这样的:
Array ( [0] => x [1] => y ) Array ( [0] => zzz [1] => y ) Array ( [0] => zzz [1] => y ) Array ( [0] => zzz [1] => y ) Array ( [0] => 123 [1] => y )
You can see that the results of using array_flip()
during the assigment of $arr
to $arr2
results in differences in the subsequent changes to $arr2
, as the array_flip()
calls forces a dereference.
It doesn't seem terribly efficient, but it might work for you if $this->x->getResults()
is returning an array:
$data['x'] = array_flip(array_flip($this->x->getResults()));
$data['y'] = $data['x'];
见 this (unanswered) thread再举个例子。
如果返回数组中的所有内容都是对象,那么复制对象的唯一方法是使用 clone()
,并且您必须遍历 $data[' x']
并将每个元素克隆到 $data['y']
中。
例子:
$data['x'] = $this->x->getResults();
$data['y'] = array();
foreach($data['x'] as $key => $obj) {
$data['y'][$key] = clone $obj;
}
关于php按值而不是引用复制数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1190026/