所以我有这个函数,它返回一个对传入数组的特定点的引用。我想调用unset,然后从数组/引用中删除结果,但是调用unset只会删除引用,而不是原始数组中的数据。有什么想法吗?
答案 0 :(得分:4)
设置对null
的引用将破坏引用(和任何其他引用)链接的数据。
有关详细信息,请参阅手册中的Unsetting References。基本上你想要做以下事情(摘自评论):
$a = 1;
$b =& $a;
$c =& $b; //$a, $b, $c reference the same content '1'
$b = null; //All variables $a, $b or $c are unset
在你的情况下,它看起来像这样:
$a =& getArrayReference($whatever);
$a = null;
修改强>
要清除任何误解,这是取消设置数组引用时的结果:
$arr = array('x','y','z');
$x =& $arr[1];
unset($x);
print_r($arr);
//gives Array ( [0] => x [1] => y [2] => z )
$x =& $arr[1];
$x = null;
print_r($arr);
//gives Array ( [0] => x [1] => [2] => z )
注意第二个数组索引在第一个示例中使用unset()
没有删除它的内容,但设置引用null
的第二个示例实现了这一点。
注意:如果你需要取消设置数组索引,我对你是否做不清楚,那么你需要找到一种方法来引用数组的键而不是该值,可能是通过改变函数的返回值。
答案 1 :(得分:1)
预期的行为是取消设置引用不会取消设置被引用的变量。一种解决方案是返回密钥而不是值,并使用它来取消设置原始值。
答案 2 :(得分:0)
请注意,unset
on references的行为是设计使然。您可以返回要删除的元素的索引,或者如果数组不平坦则返回索引数组。
例如,您可以使用以下功能:
function delItem(&$array, $indices) {
$tmp =& $array;
for ($i=0; $i < count($indices)-1; ++$i) {
$key = $indices[$i];
if (isset($tmp[$key])) {
$tmp =& $tmp[$key];
} else {
return array_slice($indices, 0, $i+1);
}
}
unset($tmp[$indices[$i]]);
return False;
}
或者,如果您更喜欢例外,
function delItem(&$array, $indices) {
$tmp =& $array;
while (count($indices) > 1) {
$i = array_shift($indices);
if (isset($tmp[$i])) {
$tmp =& $tmp[$i];
} else {
throw new RangeException("Index '$i' doesn't exist in array.");
}
}
unset($tmp[$indices[0]]);
}