Page 1 of 1
Simple array re-structure problem
Posted: Fri May 02, 2008 10:58 am
by jyoun
I want to turn this:
Code: Select all
$dependencies = array(
'A' => 'B',
'B' => null,
'C' => 'A',
'D' => 'A',
'E' => 'B',
'F' => 'C',
'G' => 'C'
)
into a tree-structure like this:
Code: Select all
array(
'B' => array (
'A' => array (
'C' => array (
'F',
'G'
),
'D'
),
'E'
)
)
Should be pretty simple, I just can't figure it out! Anyone care to help me?
Re: Simple array re-structure problem
Posted: Fri May 02, 2008 11:17 am
by aceconcepts
What are you trying to achieve?
Re: Simple array re-structure problem
Posted: Fri May 02, 2008 11:33 am
by jyoun
sorry, I shoulda been more clear. I want to build a dependency tree array. I don't know how else to explain it. I've another function already for determining the "chain", or in other words, what parents are associated with a particular object. That looks like this:
Code: Select all
// returns all parents leading up to an object
function get_dep_chain($obj) {
global $dependencies;
$parent = $dependencies[$obj];
$chain[] = $parent;
while ($parent != null) {
$parent = $dependencies[$parent];
if (in_array($parent, $chain)) return $parent;
else $chain[] = $parent;
}
$chain = array_reverse($chain); // optional?
return $chain;
}
So, $dependencies was defined earlier in my first post. Performing this function like this:
Code: Select all
$chain = get_dep_chain('F');
print_r(is_array($chain) ? $chain : "There's a feedback loop @ $chain!\n");
would result in output that looks like
Code: Select all
Array
(
[0] =>
[1] => B
[2] => A
[3] => C
)
So, I got that part working, now I want to be able to show dependencies in a tree-style structure, not unlike a file structure really - just rename "chain" to "pathname" and maybe that makes more sense.
Gee, I hope I'm making myself clear.
