I have a bunch of name-parentname pairs, that I turned into a heirarchical tree structure. So for example, these are my pairings:
Child : Parent
H : G
F : G
G : D
E : D
A : E
B : C
C : E
D : 0
Which after using this function found here.
$array = array('H' => 'G', 'F' => 'G', ..., 'D' => null);
function to_tree($array)
{
$flat = array();
$tree = array();
foreach ($array as $child => $parent) {
if (!isset($flat[$child])) {
$flat[$child] = array();
}
if (!empty($parent)) {
$flat[$parent][$child] =& $flat[$child];
} else {
$tree[$child] =& $flat[$child];
}
}
return $tree;
}
$array_tree = to_tree($array)
I get an array like this:
Array
(
[7] => Array
(
[24] => Array
(
)
[38] => Array
(
)
[78] => Array
(
)
[103] => Array
(
)
[121] => Array
(
)
[163] => Array
(
[162] => Array
(
)
[213] => Array
(
)
[214] => Array
(
)
[215] => Array
(
)
)
...
What I need is to get an array of the key i’m looking for plus all the children keys.
Let’s say I’m looking for key 7, so I would get an array like this one:
Array
(
[0] => 7
[1] => 24
[2] => 38
[3] => 78
[4] => 103
[5] => 121
[6] => 163
[7] => 162
[8] => 213
[9] => 214
[10] => 215
...
)
But I also need to look on keys like 163 and get:
Array
(
[0] => 163
[1] => 162
[2] => 213
[3] => 214
[4] => 215
)
I think is not that hard for experienced users, but I can’t quite figure it out.
2
Answers
After digging a lot I came up with this solution:
This is working great, I don't know if it's the best solution.