PHP:检查的对象/数组是一个参考 [英] PHP: check if object/array is a reference

查看:120
本文介绍了PHP:检查的对象/数组是一个参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不好意思问,其晚,我想不通的方式来做到这一点...谁能帮助?

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房间显示:

var_dump $room shows:

...
'users' => &
...

这意味着用户是一个参考。

Which means "users" is a reference.

我愿做这样的事情:

foreach($room as $key => $val) {
    if(is_reference($val)) unset($room[$key]);
}

主要目标是到阵列复制没有任何引用。

The main goal is to copy the array WITHOUT any references.

这可能吗?

感谢您。

推荐答案

您可以测试通过数组的一个副本,然后改变与测试依次在每个条目多维数组引用:

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:

$roomCopy = $room;
foreach ($room as $key => $val) {
  $roomCopy[$key]['_test'] = true;
  if (isset($room[$key]['_test'])) {
    // It's a reference
    unset($room[$key]);
  }
}
unset($roomCopy);

使用您的数据。例如, $房['家具'] $ roomCopy ['家具'] 将是单独的阵列(如 $ roomCopy $房的复印件),因此增加一个新的关键1韩元 ŧ影响其他。但是, $房['用户'] $ roomCopy ['用户'] 将是相同的引用 $用户阵列(因为它是被复制的参考,而不是数组),所以当我们添加一键 $ roomCopy ['用户'] 它是可见的 $房['用户']

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'].

这篇关于PHP:检查的对象/数组是一个参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆