PHP - 通过多维数组回溯以检查递归问题

时间:2014-09-08 17:36:06

标签: php recursion multidimensional-array

我有一个PHP数组,它基于ID来概述对象之间的父子关系。该数组可能无限深,但唯一的规则是"您可能不会将子ID添加到父级,其中子ID是所述父级的父级或祖父级(或曾祖父级等)# 34;,以排除递归循环。

例如:

<?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' => []
        ]
    ]
];
?>

我尝试编写一个函数,当ID可能作为子项添加到另一个ID时检查递归问题。它将接收一个ID($candidate_id)并尝试将其添加为另一个ID($parent_id)的子项,并检查现有数组($relationship)一直备份如果候选者没有显示为$ parent的父,祖父母等,则返回true;如果候选添加将通过添加引起递归问题,则返回false。

从上面的$good_relationship,它会返回true我将ID 3添加到ID 5,但如果我将ID 7添加到ID 5,则false

这是我到目前为止所拥有的,但我知道它已经离开 - 它只是检查候选人ID的直接祖父母。

<?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;
}

?>

在这种情况下,我已经查看了array_walk_recursive(),但如果$good_relationship有多个元素(它总是会有),那么回调将不知道如何&# 39;深&#39;它在功能范围内,这一切都变成了一场噩梦。

有人可以帮我吗?

0 个答案:

没有答案