-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathдерево.txt
54 lines (39 loc) · 1.68 KB
/
дерево.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
function array2tree($source_arr, $pid, $key_children='children', $key_id='id', $key_pid='parent_id')
{
$tree=array();
if (empty($source_arr))
return $tree;
_array2treer($source_arr, $tree, $pid, $pid, $key_children, $key_id, $key_pid);
return $tree;
}
function _array2treer($source_arr, &$_this, $pid, $_this_id, $key_children, $key_id, $key_pid)
{
// populate current children
foreach ($source_arr as $value)
if ($value[$key_pid]==$_this_id)
$_this[$key_children][$value[$key_id]]=$value;
//print('$_this[$key_children]='.$value.'<br/>');
if (isset($_this[$key_children]))
{
// populate children of the current children
foreach ($_this[$key_children] as $value)
_array2treer($source_arr, $_this[$key_children][$value[$key_id]], $pid, $value[$key_id], $key_children, $key_id, $key_pid);
// make the tree root look pretty (more convenient to use such tree)
if ($_this_id===$pid)
$_this=$_this[$key_children];
}
}
$family = [
['id' => 1, 'name' => 'Ñûí Âàñÿ', 'parent_id' => 2],
['id' => 3, 'name' => 'Äåäóøêà Èâàí', 'parent_id' => 0],
['id' => 2, 'name' => 'Ïàïà Êîëÿ', 'parent_id' => 3],
['id' => 4, 'name' => 'Äî÷ü Íèíà', 'parent_id' => 2],
['id' => 5, 'name' => 'Âíó÷êà Àíÿ', 'parent_id' => 1],
];
print('<pre>'); print_r($family);print('</pre>');
$tree=array2tree($family,0);
?>
<p>Ðåçóëüòàò:</p>
<?php
print('<pre>'); print_r($tree);print('</pre>');
?>