我有这种格式的数据:
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
现在我想创建包含该数据的嵌套数组,我将其编码为:
<?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);
?>
但这只会降到第3级,而不是更进一步。输出如下:
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 和 sub_sub_sub_two 不在输出中,如何使我的代码递归,所以无论数据中存在多少级别或关系,它仍然有效?
答案 0 :(得分:1)
从你的代码我知道“一个”意味着“一个”在顶层,否则“a,b”意味着“a”是“b”的孩子。
您可以将所有链接转换为关联数组格式,如果sub_a是'a'的子级,则$ links ['a'] ='sub_a'。 然后使用其更深和更深的键的子项递归填充$嵌套。
示例代码如下:
<?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);
?>
输出:
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] =>
)
)
)
)