1

I need to remove an object from an array in php but I need the object reference to still exist, when I tried using unset() as described here it unset both the array element and the object itself, how can I remove the reference from the array without destroying the object?

my code looks like the following:

$this->array[id] = myobject;
unset($this->array[$id]);
4

3 回答 3

2

这段代码对我来说很好:

$my_var = 1;
$my_array = array();
$id = 0;

$my_array[$id] = $my_var;
print_r($my_array);
print_r($my_var);

unset($my_array[$id]);
print_r($my_array);
print_r($my_var);

最后,我已经从 中清除了$id(0) 索引$my_array,by$my_var仍然等于1

于 2013-07-26T17:46:32.147 回答
1

您是否尝试在销毁数组引用之前保留对象的引用?

$user = new User('name','surname');
$myUserReference = $user;
$data = array('user'=> $user);

print_r($data);
unset($data['user']);
print_r($data);

这应该打印一个包含 $user 对象的数组和一个空数组。您应该在 $myUserReference var 中有对 $user 对象的引用

于 2013-07-26T18:02:55.700 回答
1

您需要此对象的另一个参考。看看这段代码:

<?php
$var = 1;

$data = array("id" => &$var);
unset($data['id']);

var_dump($var);
var_dump($data);

它打印:

int(1)
array(0) {
}

只需在其他地方保留对该对象的另一个引用。

于 2013-07-26T17:40:16.640 回答