PHP interesting recursion with element's removing
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;
}
精彩评论