php 在层次结构数组中进行移位
我有下一个数组:
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;
}
你能帮我修改一下这个功能吗?
非常感谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个功能,它应该按照你的要求做。
您的第一个数组也必须是有效的子数组,您可以针对您列出的数组这样调用它。
Try this function, it should do as you asked.
Your FIRST array MUST be a valid children array also, you can call it like this against your array you listed.
在取消设置节点之前,您需要将子节点附加到该节点的父节点。这不会发生(代码仅取消设置),因此孩子们丢失了。
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.