2009-12-30 19 views
2

所以我有这个函数,它返回一个指向传入数组的特定点的引用。我想调用unset,然后从数组/引用中删除结果,但调用取消设置只会删除引用,而不是原始数组中的数据。有什么想法吗?unsetting php reference

回答

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) 

请注意,第二个数组索引在第一个示例中没有将其内容删除,但是将参考设置为null的第二个示例完成了此操作。

注意:如果您还需要取消设置数组索引以及我有点不清楚您是否需要,那么您需要找到一种方法来引用数组的键的价值,可能通过改变你的函数的返回值。

+0

这是不正确的。这会将$ a,$ b和$ c设置为“null”。考虑这个: <?php $ a = array('foo','bar'); $ b = &$a[0]; $ b = null; var_dump($ a); 数组$ a中仍然会有两个值; – 2009-12-30 00:19:51

+0

@runish:这就是原始海报试图完成的内容 - 被引用内容的破坏。然而,你的例子是错误的。仍然会有两个数组索引,但数据将会消失。 – zombat 2009-12-30 00:25:18

+0

只有内容不被破坏,它只是无效。 – 2009-12-30 00:27:40

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]]); 
} 
+0

如果我得到一个索引数组(其中索引数组的大小为n),我如何访问该值以取消它的设置? – onassar 2009-12-30 02:45:32

1

预期行为清除一个参考不取消变量被引用。一种解决方法是返回键而不是值,并使用它来取消原始值。