在PHP中具有自身引用的数组
我想用php实现这一点,但这有可能吗?如果有,如何实现 两个元素的数组,第一个是嵌套数组的数组(内容和深度未知,您只知道每个数组都有一个id),第二个是对第一个元素中每个数组的引用数组。大概是这样的:在PHP中具有自身引用的数组,php,arrays,reference,Php,Arrays,Reference,我想用php实现这一点,但这有可能吗?如果有,如何实现 两个元素的数组,第一个是嵌套数组的数组(内容和深度未知,您只知道每个数组都有一个id),第二个是对第一个元素中每个数组的引用数组。大概是这样的: $all = Array ( 'nested_arrays' => Array( 'id0' => Array( 'id8' => Array( ... )... )... 'references' => Ar
$all = Array (
'nested_arrays' => Array(
'id0' => Array(
'id8' => Array(
...
)...
)...
'references' => Array(
'id0' => (reference to Array id0),
'id8' => (reference to Array id8),
...
)
)
$all = [
'nested_arrays' => [
'id0' => [
'id8' => [
'hello'
],
'id3' => [
'id6' => 'apple'
]
]
],
];
$all['references']['id0'] = &$all['nested_arrays']['id0'];
$all['references']['id8'] = &$all['nested_arrays']['id0']['id8'];
$all['references']['id6'] = &$all['nested_arrays']['id0']['id3']['id6'];
然后您可以访问每个阵列而不知道它在哪里,如
$all['references']['id8']
你甚至可以这样做
unset($all['references']['id8'])
…是的,或者您可以吗?我宁愿创建一个实现迭代器接口的对象。对象本质上是通过引用传递的
$id0 = new MyIterator($array);
$all = [
'nested_arrays' => [
'id0' => $id0
],
'references' => [
'id0' => $id0
]
];
另一种方法是递归迭代“嵌套数组”并填充“引用”数组
foreach ($nested as $k => $v) {
// Custom recursive iteration
...
$all['references'][$k] = &$v;
}
通常,您不能通过取消设置对象的引用来删除原始值或对象。只有当指向该值的所有指针都未设置时,原始值才会被销毁。您必须在数组中循环。您可以通过在数组的引用中存储引用来执行第一个操作,如下所示:
$all = Array (
'nested_arrays' => Array(
'id0' => Array(
'id8' => Array(
...
)...
)...
'references' => Array(
'id0' => (reference to Array id0),
'id8' => (reference to Array id8),
...
)
)
$all = [
'nested_arrays' => [
'id0' => [
'id8' => [
'hello'
],
'id3' => [
'id6' => 'apple'
]
]
],
];
$all['references']['id0'] = &$all['nested_arrays']['id0'];
$all['references']['id8'] = &$all['nested_arrays']['id0']['id8'];
$all['references']['id6'] = &$all['nested_arrays']['id0']['id3']['id6'];
然后检查输出:
echo '<pre>'. print_r($all['references']['id8'], true) . '</pre>';
echo '<pre>'. print_r($all['references']['id6'], true) . '</pre>';
但是,您不能在这个问题上使用unset,因为这只会删除数组的元素,而不会删除它所指向的数组元素。非常感谢!两个很好的答案,是的,我应该记得,你不能取消引用本身,只有引用。