PHP有趣的递归与元素的删除

时间:2011-02-16 11:26:27

标签: php arrays recursion tree multidimensional-array


我有一个多维数组。并且一些数组的元素具有“非活动”标志。我需要删除这些元素。但下线元素应该会上升。我写了一个函数,但它的工作错了。仅当第一个数组元素处于非活动状态时,它才能正
功能:

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

测试阵列:

$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()
        )
        )
    )
    )
);

测试:

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

1 个答案:

答案 0 :(得分:0)

这是一种怀疑方法:

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