我有一个这种格式的txt文件
-Main
--Sub
--Next sub
---Sub Sub
--Last sub
-Next Main
-Last Main
--Sub
--Next sub
我需要将其转换为嵌套数组
Array(
"Main" => array("Sub","Next sub" => array("Sub Sub")),
);
在PHP中有没有任何递归函数可以做到这一点? 非常感谢
答案 0 :(得分:0)
我认为简单地爆炸文件内容就可以完成这项工作,以便让您入门:
$file = fopen('path/to/file.txt', "r");
$array = explode('/r',$file);
这是基本的,但是从这里开始,您可以将其操作为嵌套数组。
答案 1 :(得分:0)
也许不是很漂亮,但代码可以运作。
$str = "
-Main
--Sub level 2
--Next sub level 2
---Sub Sub1 level 3
---Sub Sub2 level 3
--Last sub level 2
-Next Main
-Last Main
--Sub level 2
--Next sub level 2
--Next sub level 2
--Next sub level 2
---Next sub1 level 3
---Next sub2 level 3
---Next sub3 level 3
--Next sub level 2
-Next sub
--Next sub level 2
--Next sub level 2
";
$a = explode("\n", $str);
$last_count = 1;
$level = array();
$level1 = array();
$level2 = array();
$level3 = array();
$max_level = 0;
$min_level = 1;
foreach($a as $key => $val)
{
$count = substr_count($val, '-');
if ($max_level < $count)
{
$max_level = $count;
}
}
foreach($a as $key => $val)
{
$count = substr_count($val, '-');
$val = trim($val, '-');
if ($count > 0)
{
if ($count == $min_level)
{
$level1[] = $level2;
if ($last_count == 2)
{
$level1[] = $val;
}
$level1[] = $level2;
$level2 = array();
$level1[] = $val;
}
elseif ($count == ($max_level - 1) && ($last_count >= $min_level))
{
if ($last_count == $max_level)
{
array_pop($level2);
$level2[$name2] = $level3;
$level3 = array();
}
$level2[] = $val;
$name2 = $val;
}
elseif ($count == $max_level && ($last_count >= ($min_level + 1)))
{
$level3[] = $val;
}
$last_count = $count;
}
}
$level1[] = $level2;
$level1 = array_filter($level1);
$arr = array();
foreach($level1 as $key)
{
$arr[$var] = is_array($key) ? $key : '';
$var = $key;
}
$arr = array_filter($arr);
echo '<pre>';
print_r($arr);
echo '</pre>';
结果:
Array
(
[Main] => Array
(
[0] => Sub level 2
[Next sub level 2] => Array
(
[0] => Sub Sub1 level 3
[1] => Sub Sub2 level 3
)
[1] => Last sub level 2
)
[Last Main] => Array
(
[0] => Sub level 2
[1] => Next sub level 2
[2] => Next sub level 2
[Next sub level 2 ] => Array
(
[0] => Next sub1 level 3
[1] => Next sub2 level 3
[2] => Next sub3 level 3
)
[3] => Next sub level 2
)
[Next sub] => Array
(
[0] => Next sub level 2
[1] => Next sub level 2
)
)