我有下一个数组:
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()
)
)
)
)
)
我需要从这个数组中删除[inactive] = true的元素。但我的问题在旁边。我应该移动数组元素。 输出应该是:
Array(
[id] => 1
[children] => Array(
[4] => Array(
[id] => 4
[children] => Array()
)
[3] => array(
[id] => 3
[children] => Array(
)
)
)
)
这是我的功能。但它删除了包含所有子元素的数组元素。
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;
}
你能帮我修改这个功能吗?
非常感谢。
答案 0 :(得分:1)
在取消设置节点之前,您需要将子节点附加到节点的父节点。这不会发生(代码只会取消设置),因此孩子们会丢失。
答案 1 :(得分:1)
试试这个功能,应该按照你的要求做。
<?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;
} ?>
你的FIRST数组也必须是一个有效的子数组,你可以对你列出的数组这样调用它。
deleteInactive(array('1' => $array));