I have some data in this format:
one,one
two,two
sub_one,one
sub_two,two
sub_sub_one,sub_one
sub_sub_two,sub_two
sub_sub_sub_one,sub_sub_one
sub_sub_sub_two,sub_sub_two
Now I want to create nested arrays that contains that data, I coded this:
<?php
$lines[] = "one,one";
$lines[] = "two,two";
$lines[] = "sub_one,one";
$lines[] = "sub_two,two";
$lines[] = "sub_sub_one,sub_one";
$lines[] = "sub_sub_two,sub_two";
$lines[] = "sub_sub_sub_one,sub_sub_one";
$lines[] = "sub_sub_sub_two,sub_sub_two";
foreach($lines as $line)
{
$tmp = explode(",", $line);
$array[$tmp[1]][$tmp[0]] = $tmp[0];
}
foreach($array as $key => $value)
{
foreach($array[$key] as $value2)
{
if(array_key_exists($value2, $array) && $value2 != $key)
{
$array[$key][$value2] = $array[$value2];
$unset[] = $value2;
}
else
{
unset($array[$key]);
}
}
}
foreach($unset as $un)
{
unset($array[$un]);
}
print_r($array);
?>
But this only goes down to the 3rd level and no futher. The output looks like this:
Array
(
[one] => Array
(
[sub_one] => Array
(
[sub_sub_one] => sub_sub_one
)
)
[two] => Array
(
[sub_two] => Array
(
[sub_sub_two] => sub_sub_two
)
)
)
sub_sub_sub_one and sub_sub_sub_two are not in the output, how can I make my code recursive so no matter how many levels or relation exists in the data it will still work?
Hmm from your code I understand that "one,one" means "one" is at top-level, and otherwise "a,b" means "a" is child of "b".
You could just convert all links into an associative array format, such that $links['a'] = 'sub_a' if sub_a is a child of 'a'. Then populate $nested recursively with the children of its deeper and deeper keys.
A sample code follows:
And the output: