开发者

PHP interesting recursion with element's removing

I have a multidimensional array. And some of array's eleme开发者_JS百科nts have 'inactive' flag. I need to remove this elements. But downline elements should be go up. I wrote a function, but it works wrong. It works fine only if first array element is inactive.

Function:

function deleteInactive($children, $generation = 0)
{
    $generation++;
    $copy = $children;
    if (!empty($copy) && is_array($copy)) {
    foreach ($copy as $key => $v) {
        $inactive = false;
        if (array_key_exists('inactive', $v) && $v['inactive'] === true) {      
        $nextGeneration = $generation - 1;
        $inactive = true;
        $children = deleteInactive($v['children'], $nextGeneration);
        unset($children[$key]);
        } else {
        $nextGeneration = $generation;
        if (!empty($v['children']) && is_array($v['children'])) {
            $children[$key] = $v;
            $children[$key]['children'] = deleteInactive($v['children'], $generation);
        }
        }
        if (!$inactive) {
        $children[$key]['generation'] = $nextGeneration;
        }
    }
    }
    return $children;
}

Test array:

$tree = array(
    'id' => 1000,
    'generation' => 0,
    'children' => array(
    1002 => array(
        'id' => 1002,
        'generation' => 1,
        'children' => array(
        1005 => array(
            'id' => 1005,
            'generation' => 2,
            'inactive' => true,
            'children' => array()
        )
        )
    ),
    1006 => array(
        'id' => 1006,
        'generation' => 1,
        'inactive' => true,
        'children' => array(
        1007 => array(
            'id' => 1007,
            'generation' => 2,          
            'children' => array()
        )
        )
    ),
    1008 => array(
        'id' => 1008,
        'generation' => 1,      
        'children' => array(
        1009 => array(
            'id' => 1009,
            'generation' => 2,
            'children' => array()
        )
        )
    )
    )
);

Testing:

print_r($tree);
$tree['children'] = deleteInactive($tree['children']);
print_r($tree);


It is a wright method:

public function deleteInactive($children, $g = 0)
{
    $generation++;
    $copy = $children;
    if (!empty($copy) && is_array($copy)) {
        foreach ($copy as $k => $v) {
        $inactive = false;
        if (array_key_exists('inactive', $v) && $v['inactive']) {
            $children += $this->deleteInactive($v['children'], ($generation - 1));
            unset ($children[$k]);
            $inactive = true;
        } else {
            $children[$k] = $v;
            $children[$k]['children'] = $this->deleteInactive($v['children'], $generation);
        }
        if (!$inactive) {
            $children[$k]['generation'] = $generation;
        }
        }
    }
    return $children;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜