PHP:在深度数组中查找元素,然后修改每个父元素



我对多维数组的深度程度各不相同。我想找到 UserId 所在的元素(请参阅下面的示例数组(,然后将键/值对 ([show] => true( 添加到匹配的元素和每个父数组中。可能有多个匹配项需要修改父项。

我有这个:

Array
(
[0] => Array
(
[id] => 3
[parent_id] => 0
[ownerEntityId] => 2
[children] => Array
(
[0] => Array
(
[id] => 15
[parent_id] => 3
[ownerEntityId] => 14
[children] => Array
(
[0] => Array
(
[id] => 17
[parent_id] => 15
[ownerEntityId] => 
[userId] => 2
)
[1] => Array
(
[id] => 18
[parent_id] => 15
[ownerEntityId] => 
)
[2] => Array
(
[id] => 19
[parent_id] => 15
[ownerEntityId] => 
)
)
)
[1] => Array
(
[id] => 11
[parent_id] => 3
[ownerEntityId] => 
)
)
)
[1] => Array
(
[id] => 26
[parent_id] => 1
[ownerEntityId] =>
[children] => Array
(
[0] => Array
(
[id] => 23
[parent_id] => 26
[ownerEntityId] => 24
[1] => Array
(
[id] => 41
[parent_id] => 26
[ownerEntityId] => 
)
)
)

我想要这个:

Array
(
[0] => Array
(
[id] => 3
[parent_id] => 0
[ownerEntityId] => 2
[show] => true //***Added
[children] => Array
(
[0] => Array
(
[id] => 15
[parent_id] => 3
[ownerEntityId] => 14
[show] => true //***Added
[children] => Array
(
[0] => Array
(
[id] => 17
[parent_id] => 15
[ownerEntityId] =>
[show] => true //***Added
[userId] => 2
)
[1] => Array
(
[id] => 18
[parent_id] => 15
[ownerEntityId] => 
)
[2] => Array
(
[id] => 19
[parent_id] => 15
[ownerEntityId] => 
)
)
)
[1] => Array
(
[id] => 11
[parent_id] => 3
[ownerEntityId] => 
)
)
)
[1] => Array
(
[id] => 26
[parent_id] => 1
[ownerEntityId] =>
[children] => Array
(
[0] => Array
(
[id] => 23
[parent_id] => 26
[ownerEntityId] => 24
[1] => Array
(
[id] => 41
[parent_id] => 26
[ownerEntityId] => 
)
)
)

我一直在搞砸多个递归函数,这些函数让我惨遭失败。

https://ideone.com/HoJPry

function hasUserId (&$el) {
if(isset($el['children'])) {
$ret = false;
foreach($el['children'] as &$child) {
if(hasUserId($child)) {
$ret=true;
}
}
if($ret) {
$el['show']=true;
return true;
}
} ;
if (isset($el['user_id'])) {
$el['show']=true;
return true;
}
}
foreach($top as $i => $t)
{
foreach($t['children'] as $n => $mid)
{
foreach($mid['children'] as $x => $bottom)
{
if($bottom['id'] !== $target_id)
continue;
$top[$i]['show'] = true;
$top[$i]['children'][$n]['show'] = true;
$top[$i]['children'][$n]['children'][$x]['show'] = true;
}
}
}

相关内容

最新更新