Как я могу сделать массив двоичного дерева из массива?

У меня есть множество людей:

array(
array(
'name' => 'John',
'id' => 1,
'mother_id' => 2,
'father_id' => 3
),
array(
'name' => 'Lucy',
'id' => 2,
'mother_id' => 5,
'father_id' => 4
),
array(
'name' => 'Jim',
'id' => 3,
'mother_id' => 7,
'father_id' => 9
),
array(
'name' => 'Paul',
'id' => 4,
'mother_id' => 534,
'father_id' => 54
),
array(
'name' => 'Laura',
'id' => 5,
'mother_id' => 554,
'father_id' => 51
),
array(
'name' => 'Vanessa',
'id' => 7,
'mother_id' => 5354,
'father_id' => 514
),
array(
'name' => 'Adam',
'id' => 9,
'mother_id' => 245354,
'father_id' => 514234
),
);

И я хочу получить это:

array(
array(
'person' => array(
'name' => 'John',
'id' => 1,
'mother_id' => 2,
'father_id' => 3
),
'parents' => array(
'mother' => array(
'person' => array(
'name' => 'Lucy',
'id' => 2,
'mother_id' => 5,
'father_id' => 4
),
'parents' => array(
'mother' => array(
'person' => array(
'name' => 'Laura',
'id' => 5,
'mother_id' => 554,
'father_id' => 51
),
'parents' => array(...)
),
'father' => array(
'person' => array(
'name' => 'Paul',
'id' => 4,
'mother_id' => 534,
'father_id' => 54
),
'parents' => array(...)
),
)
),
'father' => ...
)

Итак, Джон — это ребенок, у которого есть мать и отец, у отца есть мать и отец, у матери есть мать и отец и т. Д., И он пишет сценарий, который делает что-то, но не то, что я хочу точно

function parseTree(& $tree, $root = null) {
$return = null;

foreach ($tree as $key=> $item){

if ($item['id'] == $root){

$return = [
'person' => $item,
'parents' => [
'father' => parseTree($tree, $item['father_id'])
]
];

unset ($tree[$key]);
}elseif($item['id'] == $root){
$return = [
'person' => $item,
'parents' => [
'father' => parseTree($tree, $item['mother_id'])
]
];

unset ($tree[$key]);
}
elseif ($root == null) {

$return = [
'person' => $item,
'parents' => [
'father' => parseTree($tree, $item['father_id']),
'mother' => parseTree($tree, $item['mother_id'])
]
];

unset ($tree[$key]);
}
}
return $return;
}

Как я могу заставить это работать? Или для этого есть подходящие библиотеки?

0

Решение

У тебя почти было это. Я бы сделал это следующим образом:

function parseTree(&$tree, $root = null)
{
$return = null;
foreach ($tree as $key => $item) {
if ($root == null || $item['id'] == $root) {
$return = [
'person' => $item,
'parents' => [
'father' => parseTree($tree, $item['father_id']),
'mother' => parseTree($tree, $item['mother_id'])
]
];
unset ($tree[$key]);
}
}
return $return;
}
0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector