【发布时间】:2013-11-20 22:12:54
【问题描述】:
我已经被这个问题困扰了一段时间,并决定向伟大的 stackoverlow 社区寻求建议。我正在为我的问题寻求解决方案,但在知道解决方案后我会学到很多东西。
我有一个在这里看到的数组
Array
(
[0] => Array
(
[id] => 1
[parent] => 0
)
[1] => Array
(
[id] => 2
[parent] => 0
)
[2] => Array
(
[id] => 3
[parent] => 0
[children] => Array
(
[0] => Array
(
[id] => 4
[parent] => 3
[children] => Array
(
[0] => Array
(
[id] => 7
[parent] => 4
[selected] => 1
)
)
)
[1] => Array
(
[id] => 5
[parent] => 3
)
[2] => Array
(
[id] => 6
[parent] => 3
)
)
)
)
正如您所见,数组元素有时会嵌套“子元素”,而这些元素可能会有“子元素”等,但最终您会看到一个值为“SELECTED”= true 的数组。我需要的是一种使其所有父母都成为“SELECTED”的方法。
我在 PHP 中有这个函数,但它拒绝工作。现在我的大脑被炸了
private function selectParent($tree)
{
foreach ($tree as $key => $branch)
{
if(isset($branch['children']))
{
$tree[$key]['children'] = self::selectParent($tree[$key]['children']);
}
if(isset($branch['children']))
{
foreach ($branch['children'] as $child)
{
if(isset($child['selected']))
{
$tree[$key]['selected'] = true;
}
}
}
}
return $tree;
}
非常感谢任何帮助/提示/解决方案。
谢谢 马丁
更新
我将我的函数更新为这个并且它可以工作
private function selectParent($tree, $id = null)
{
$newTree = array();
foreach ($tree as $key => $branch)
{
if(isset($branch['children']))
{
$branch['children'] = self::selectParent($branch['children']);
}
if(isset($branch['children']))
{
foreach ($branch['children'] as $child)
{
if(isset($child['selected']))
{
$branch['selected'] = true;
}
}
}
$newTree[] = $branch;
}
return $newTree;
}
不过,我会研究建议的方法。 感谢那些回复帮助的人!
【问题讨论】:
-
请原谅我在代码块上的失败尝试
-
就在我编辑它时,一位管理员为我完成了它。对不起,谢谢!
-
我非常怀疑它“拒绝工作”
-
好吧,它没有“拒绝工作”,我的解决方案尝试失败了
标签: php arrays loops multidimensional-array