问题
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?
回答1:
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:
<?php
$nested = array();
$links = array();
// first, create a structure that contains the connections between elements
foreach ($lines as $line) {
list($child, $parent) = explode(",", $line);
if ($child == $parent) {
$nested[$parent] = null;
} else {
// add it to the children of parent
$links[$parent][] = $child;
}
}
function process(&$arr) {
global $links;
foreach ($arr as $key => $value) {
// no more children => stop recursion
if (!array_key_exists($key, $links)) {
$array[$key] = null;
continue;
}
// insert its children
$arr[$key] = array_flip($links[$key]);
// recurse down
process($arr[$key]);
}
}
process($nested);
// $nested contains your m-dim array
print_r($nested);
?>
And the output:
Array
(
[one] => Array
(
[sub_one] => Array
(
[sub_sub_one] => Array
(
[sub_sub_sub_one] =>
)
)
)
[two] => Array
(
[sub_two] => Array
(
[sub_sub_two] => Array
(
[sub_sub_sub_two] =>
)
)
)
)
来源:https://stackoverflow.com/questions/5157243/how-to-create-nested-php-arrays-recursively