PHP-回溯多维数组以检查递归问题
我有一个PHP数组,它根据对象ID勾勒出对象之间的父子关系。该数组可能无限深,但唯一的规则是“您不能向父对象添加子ID,其中子ID是所述父对象的父对象或祖父母(或曾祖父母等),为了排除递归循环 例如:PHP-回溯多维数组以检查递归问题,php,recursion,multidimensional-array,Php,Recursion,Multidimensional Array,我有一个PHP数组,它根据对象ID勾勒出对象之间的父子关系。该数组可能无限深,但唯一的规则是“您不能向父对象添加子ID,其中子ID是所述父对象的父对象或祖父母(或曾祖父母等),为了排除递归循环 例如: <?php // Good relationship: 6 and 4 are children of 7, with 5 a child of 6 and so on $good_relationship = [ 'id' => 7, 'children' =>
<?php
// Good relationship: 6 and 4 are children of 7, with 5 a child of 6 and so on
$good_relationship = [
'id' => 7,
'children' => [
[
'id' => 6,
'children' => [
[
'id' => 5,
'children' => [.. etc etc..]
]
]
],
[
'id' => 4,
'children' => []
]
]
];
// Badly-formed relationship: 6 is a child of 7, but someone added 7 as a child of 6.
$bad_relationship = [
'id' => 7,
'children' => [
[
'id' => 6,
'children' => [
[
'id' => 7,
'children' => [ ... 6, then 7 then 6 - feedback loop = bad ... ]
]
]
],
[
'id' => 4,
'children' => []
]
]
];
?>
在本例中,我已经查看了array\u walk\u recursive()
,但是如果$good\u relationship
包含多个元素(它总是这样),回调将不知道它在函数中的“深度”,这一切都会成为一场噩梦
这里有人能帮我吗?也许我把事情简化得太多了,但你不能在没有更多的父母出现之前递归地寻找父母吗?同时检查并在必要时返回。Cheers RST-PHP的数组处理似乎没有一个本机函数,您可以在其中引用数组的父级。我发现了另一个SO问题,这个问题的答案是共享链接。也许做数组翻转或数组值,然后检查isset或其他更简单。www.php.net上发布的一些示例可能满足您的要求。干杯RST-array_flip和array_值似乎只用于处理一维数组,但我明白您的意思。感谢可能的副本
<?php
public function check_candidate($array, $candidate_id, $parent_id, &$grandparent_id = 0)
{
$reply_array = [];
foreach($array as $action)
{
// If $action['id'] is the same as the grandparent,
if($grandparent_id == $action['id'])
{
return false;
}
$grandparent_id = $action['id'];
if(isset($action['children']) && count($action['children']) >= 1)
{
$this->check_candidate($action['children'], $candidate_id, $parent_id, $grandparent_id);
}
}
return true;
}
?>