开发者

PHP: Recursive array function

开发者 https://www.devze.com 2023-01-01 19:13 出处:网络
I want to create a function that returns the full path from a set node, back to the root value. I tried to make a recursive function, but ran out of luck totally. What would be an appropriate way to d

I want to create a function that returns the full path from a set node, back to the root value. I tried to make a recursive function, but ran out of luck totally. What would be an appropriate way to do this? I assume that a recursive function is the only way?

Here's the array:

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

    [1] => Array
        (
        开发者_JS百科    [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
        )
)

The result I want my function to output when getting full path of node 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
        )
)

The notoriously bad example of my recursive skills:

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


assuming "id" in your sub array is that sub arrays index + 1 inside the parent array (otherwise you would need to do a search in the array each time), you could do this:

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

精彩评论

暂无评论...
验证码 换一张
取 消