2
我有一套包含父母和孩子的數據。我期望做的是創建由相互連接的數據組成的邏輯組。我已經提供了我目前的代碼,但我有一種下沉的感覺,它可以被優化。如何組合一組父母 - >孩子,孩子也可以是父母。有一個解決方案,但尋找更有效的算法
$parents= array(
'1' => array(
'2' => 'none',
'3' => 'none',
'9' => 'none'
),
'2' => array(
'4' => 'none',
'5' => 'none'
),
'6' => array(
'7' => 'none',
'8' => 'none',
'9' => 'none'
),
'10' => array(
'11' => 'none',
'12' => 'none'
)
);
$groups = array();
foreach($parents as $parent => $children){
foreach(array_keys($children) as $child){
$parentgroup = -1;
$childgroup = -1;
foreach($groups as $key => $group){
if(isset($group[$parent])){
$parentgroup = $key;
}
if(isset($group[$child])){
$childgroup = $key;
}
}
if($parentgroup == -1 && $childgroup == -1){
$groups[] = array($parent => true, $child => true);
}
else {
if($childgroup == -1){
$groups[$parentgroup][$child] = true;
} else if($parentgroup == -1){
$groups[$childgroup][$parent] = true;
} else if($parentgroup != $childgroup){
foreach($groups[$childgroup] as $val => $none){
$groups[$parentgroup][$val] = true;
}
unset($groups[$childgroup]);
}
}
}
}
print_r($groups);
// Result
Array
(
[1] => Array
(
[6] => 1
[7] => 1
[8] => 1
[1] => 1
[2] => 1
[3] => 1
[9] => 1
[4] => 1
[5] => 1
)
[2] => Array
(
[10] => 1
[11] => 1
[12] => 1
)
)
我也採取了一種不同的方式,但我碰到了後面的節點的問題。這個攜帶時的項目使用,這樣我可以稍後確定重量增加的一個獎金:
function BGR($users, $group){
global $pass1;
foreach ($users as $id => $none){
$group[$id]++;
if(isset($pass1[$id])){
$children = $pass1[$id];
unset($pass1[$id]);
$group = BGR($children, $group);
}
}
return $group;
}
$groups = array();
while($pass1){
$id = key($pass1);
$parent = $pass1[$id];
unset($pass1[$id]);
$groups[] = BGR($parent, array($id => 1));
}
print_r($groups);