PHP解引用数组元素 [英] PHP dereference array elements
问题描述
我有2个阵列。
$result = array();
$row = array();
行的元素都是引用,并在不断地变化。对于 $行的每一次迭代
我要排在值复制到 $结果$ C的条目$ C>,而不是引用。
Row's elements are all references and is constantly changing. For each iteration of $row
I want to copy the values of row into an entry of $result
and not the references.
我已经找到了几个解决方案,但他们似乎都相当可怕的。
I have found a few solutions but they all seem rather awful.
$result[] = unserialize(serialize($row));
$result[] = array_flip(array_flip($row));
以上两种工作,但看起来很多不必要的和丑陋的code只是为了内容复制,而不是复制引用本身按值引用数组中。
Both of the above work but seem like a lot of unnecessary and ugly code just to copy the contents of an array of references by value, instead of copying the references themselves.
有没有做到这一点更清洁的方式吗?如果没有什么会最有效的方法是什么?
Is there a cleaner way to accomplish this? If not what would the most efficient way be?
感谢。
编辑:的建议下面的东西,如:
As suggested below something such as:
function dereference($ref) {
$dref = array();
foreach ($ref as $key => $value) {
$dref[$key] = $value;
}
return $dref;
}
$result[] = dereference($row);
另外的作品,但似乎同样丑陋。
Also works but seems equally as ugly.
推荐答案
不知道我完全理解的问题,但您可以使用递归?
Not sure I totally understand the question, but can you use recursion?
function array_copy($source) {
$arr = array();
foreach ($source as $element) {
if (is_array($element)) {
$arr[] = array_copy($element);
} else {
$arr[] = $element;
}
}
return $arr;
}
$result = array();
$row = array(
array('a', 'b', 'c'),
array('d', 'e', 'f')
);
$result[] = array_copy($row);
$row[0][1] = 'x';
var_dump($result);
var_dump($row);
这篇关于PHP解引用数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!