记住递归函数值

时间:2018-04-26 14:07:13

标签: php algorithm recursion

所以我有一个递归函数,它到达最后一个数组的末尾并打印它的值:

LEVEL : 2 ==> value: 10
LEVEL : 4 ==> key: A
LEVEL : 5 ==> value: 15
LEVEL : 7 ==> key: B
LEVEL : 8 ==> value: 45
LEVEL : 4 ==> key: C
LEVEL : 5 ==> value: 77
LEVEL : 7 ==> key: D
LEVEL : 8 ==> value: 18

因此显示以下示例:

LEVEL : 8 ==> value: 10, key: A, value: 15, key: B, value: 45
LEVEL : 8 ==> value: 10, key: C, value: 77, key: D, value: 18

在最新级别结束时(本例中为8)我想显示其父级的值而不是所有内容 - 例如:

array = array(
    array(
        "value"=>"10"
        array(
            array(
                "key"=>"A",
                array(
                    "value"=>"15",
                ),
                ... etc
            ), 
           ... etc
        ),
    ),
);

知道8只是一个例子,可能会有更多。

输入数组示例:

{{1}}

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

我在函数递归中添加另一个参数$ history,它告诉下一个级别遇到了什么。

<?php

function recursive($array, $level = 1, $history) {
    // this variable is to flag if there is an array element at current level.
    // if not, it will be latest level and output the line;
    $isLatestLevel = true;
    foreach($array as $key => $value){
        if(is_array($value)){
            recursive($value, $level + 1, $history);

            // an array element found; this is not the latest level;
            $isLatestLevel = false;
        } else{
            // create new entity to history
            $entity = $key . ": " . $value;
            $history[] = $entity;
        }
    }
    if ($isLatestLevel) {
        // output at the latest level
        // implode() means concate each history with ', ' between them
        echo "LEVEL : $level ==> " . implode(', ', $history) . PHP_EOL;
    }
}

$input = [
    'value' => '10',
    [
        [
            [
                'key' => 'A',
                [
                    'value' => '15',
                    [
                        [
                            'key' => 'B',
                            [
                                'value' => '45',
                            ]
                        ]
                    ]
                ]
            ],
            [
                'key' => 'C',
                [
                    'value' => '77',
                    [
                        [
                            'key' => 'D',
                            [
                                'value' => '18',
                            ]
                        ]
                    ]
                ]
            ]
        ],
    ],
];

recursive($input, 1, []);