我一直在這個問題上停留了一段時間,現在決定轉向偉大的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。我需要的是讓所有父母都成爲「選擇」的方式。
我在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;
}
任何幫助/技巧/解決方案非常讚賞。
感謝 馬丁
UPDATE
我我的功能更新,這和它的作品
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;
}
我會然而考慮建議的方法。 謝謝那些回覆幫助的人!
請原諒我的代碼塊 –
失敗的嘗試就在我編輯它的管理做了我。對不起,謝謝! –
我非常懷疑它*「拒絕工作」* – AbraCadaver