php shift in a hierarchy array
I have the next array:
Array(
[id] => 1
[children] => Array(
[2] => Array(
[id] => 2
[inactive] => true
[children] => Array(
[4] => Array(
[id] => 4
[children] => Array()
)
)
)
[3] => array(
[id] => 3
[children] => Array(
[5] => Array(
[id] => 5
[inactive] => true
[children] => Array()
)
)
)
)
)
I need to remove elements from this array, which have [inactive] = true. But my problem in the next. I should shift the array elements. Output should be:
Array(
[id] => 1
[children] => Array(
[4] => Array(
[id] => 4
[children] => Array()
)
[3] => array(
[id] => 3
[children] => Array(
)
)
)
)
It is my function. But it removes array element with all his subelements.
public function deleteInactive($userTree)
{
if (!empty($userTree)) {
foreach($userTree['children'] as $userId => &$user) {
if (array_key_exists('inactive', $user)) {
$userTree['children'] += $user['children'];
开发者_运维百科unset($userTree['children'][$userId]);
$this->deleteInactive($userTree);
break;
}
$this->deleteInactive($user);
}
}
return $userTree;
}
Can you help me to modify this function?
Thank you very much.
Try this function, it should do as you asked.
<?php
function deleteInactive($children) {
$copy = $children;
foreach ($copy as $key => $child) {
if (!empty($child['inactive']) && $child['inactive'] === true) {
unset($children[$key]);
$children = deleteInactive($child['children']);
} elseif (!empty($child['children']) && is_array($child['children'])) {
$children[$key]['children'] = deleteInactive($child['children']);
}
}
return $children;
} ?>
Your FIRST array MUST be a valid children array also, you can call it like this against your array you listed.
deleteInactive(array('1' => $array));
Before unsetting a node, you need to attach the children to the parent of the node. This doesn't happen (the code only unsets), so the children are lost.
精彩评论