PHP:检查对象/数组是否是引用
很抱歉问,已经晚了,我想不出办法......有人可以帮忙吗?
$users = array(
array(
"name" => "John",
"age" => "20"
),
array(
"name" => "Betty",
"age" => "22"
)
);
$room = array(
"furniture" => array("table","bed","chair"),
"objects" => array("tv","radio","book","lamp"),
"users" => &$users
);
var_dump $room 显示:
...
'users' => &
...
这意味着“用户”是一个引用。
我想做这样的事情:
foreach($room as $key => $val) {
if(is_reference($val)) unset($room[$key]);
}
主要目标是复制数组而不使用任何引用。
这可能吗?
谢谢。
Sorry to ask, its late and I can't figure a way to do it... anyone can help?
$users = array(
array(
"name" => "John",
"age" => "20"
),
array(
"name" => "Betty",
"age" => "22"
)
);
$room = array(
"furniture" => array("table","bed","chair"),
"objects" => array("tv","radio","book","lamp"),
"users" => &$users
);
var_dump $room shows:
...
'users' => &
...
Which means "users" is a reference.
I would like to do something like this:
foreach($room as $key => $val) {
if(is_reference($val)) unset($room[$key]);
}
The main goal is to copy the array WITHOUT any references.
Is that possible?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以通过制作数组的副本,然后依次更改和测试每个条目来测试多维数组中的引用:
使用示例数据,
$room['furniture']
和 < code>$roomCopy['furniture'] 将是单独的数组(因为$roomCopy
是$room
的副本),因此向其中添加一个新键不会影响对方。但是,$room['users']
和$roomCopy['users']
将引用同一个$users
数组(因为它是复制的引用,而不是数组),因此当我们向$roomCopy['users']
添加键时,它在$room['users']
中可见。You can test for references in a multi-dimensional array by making a copy of the array, and then altering and testing each entry in turn:
With your example data,
$room['furniture']
and$roomCopy['furniture']
will be separate arrays (as$roomCopy
is a copy of$room
), so adding a new key to one won't affect the other. But,$room['users']
and$roomCopy['users']
will be references to the same$users
array (as it's the reference that's copied, not the array), so when we add a key to$roomCopy['users']
it is visible in$room['users']
.我能管理的最好方法是测试两个变量,以确定一个变量是否是对另一个变量的引用:
但我怀疑这是否有多大帮助
真正肮脏的方法(也没有经过很好的测试):
要在代码中使用最后一个方法,你' d 需要做类似的事情:
因为 $val 从来都不是引用,因为它是原始数组元素的副本;并使用 &$val 使其始终成为引用
The best I can manage is a test of two variables to determine if one is a reference to the other:
but I doubt if it's much help
Really dirty method (not well tested either):
To use this last method in your code, you'd need to do something like:
because $val is never a reference as it's a copy of the original array element; and using &$val makes it always a reference
也许是递归的东西。
something recursive maybe.
这适用于 HUDGE 对象和数组。
This works with HUDGE objects and arrays.
如果你想摆脱递归元素:
输出:
if you want to get rid of recursive elements:
output: