PHP:递归数组函数

时间:2010-06-02 18:23:56

标签: php arrays oop recursion

我想创建一个函数,它返回从设置节点返回根值的完整路径。我试图做一个递归函数,但完全失去了运气。什么是适当的方法来做到这一点?我假设递归函数是唯一的方法吗?

这是数组:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Root category
            [_parent] => 
        )

    [1] => Array
        (
            [id] => 2
            [name] => Category 2
            [_parent] => 1
        )

    [2] => Array
        (
            [id] => 3
            [name] => Category 3
            [_parent] => 1
        )

    [3] => Array
        (
            [id] => 4
            [name] => Category 4
            [_parent] => 3
        )
)

结果我希望我的函数在获取节点id#4的完整路径时输出:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Root category
            [_parent] => 
        )

    [1] => Array
        (
            [id] => 3
            [name] => Category 3
            [_parent] => 1
        )

    [2] => Array
        (
            [id] => 4
            [name] => Category 4
            [_parent] => 3
        )
)

我递归技巧的臭名昭着的例子:

    function recursive ($id, $array) {

        $innerarray = array();
        foreach ($array as $k => $v) {

            if ($v['id'] === $id) {
                if ($v['_parent'] !== '') {
                    $innerarray[] = $v;
                    recursive($v['id'], $array);
                }
            }

        }
        return $innerarray; 
    }

1 个答案:

答案 0 :(得分:4)

假设子数组中的“id”是父数组中的子数组索引+ 1(否则每次都需要在数组中进行搜索),你可以这样做:

$searchNode = 4;
while ($searchNode)
{
    $result[] = $nodes[$searchNode - 1];
    $searchNode = $nodes[$searchNode - 1]["id"];
}
$result = array_reverse($result);