我最终想做的是采取一个文本文件,看起来像下面,并组织成一些我可以使用的东西,如基于选项卡空格数组。
//示例//
this is no tabbed space
this is a tabbed space
this is 2 tabbed spaces
this is no tabbed space
我想结束与:(最好使用PHP)
$list= array(no 't("string", "string", "string", one 't ("string", "string", "string",
tw0 't("string", "string", "string", etc..)),
no 't again starts new("string", "string", array());
我需要保持基于't空间的嵌套,并在没有't空间时重新开始。有什么建议或更好的方法吗?
我需要使用这个列表从一个文本文件插入到数据库作为类别和使用菜单项,有子级别和许多需要根据文本文件。
我弄清楚了如何将它们放入一个数组中,但是否有一种方法可以通过选项卡空间组织它们,或者可能通过大于一定数量的空间等?我只是在这一点上感到困惑,我尝试了许多不同的方法,但我真的迷路了。
我同意你的问题的评论,你应该重新考虑数据格式,如果它是一个选项。但是,如果不是,您可以使用以下内容来解决问题:
$list = array ();
foreach ($lines as $line)
{
$depth = NULL;
$string = preg_replace ('/'t/', '', $line, -1, &$depth);
isset ($list[$depth]) ? array_push ($list[$depth], $string) : $list[$depth] = array ($string, );
}
假设 $lines
是包含文本文件行的数组,例如file(textfile)
或explode("'n", file_get_contents(textfile))
。使用preg_replace()
,我们从每个$line
中修剪制表符,并从't
被替换为空的次数中获得$depth
。最后,修整后的字符串被附加到一个数组$list[$depth]
中——但如果它没有初始化为数组,我们将初始化为数组,并将$string
添加为第一个元素。
假设字符串中没有其他制表符,如果是这种情况,您需要使用更详细的解决方案,也许像这样,在foreach()
循环中:
$depth = 0;
$string = $line;
while (preg_match ('/^'t/', $string))
{
$string = preg_replace ('/^'t/', '', $string);
$depth ++;
}
isset ($output[$depth]) ? array_push ($output[$depth], $string) : $output[$depth] = array ($string, );
如果执行时间是必要的,这两种解决方案都不符合条件,但它们很容易实现。
还需要注意的是,该数组将作为带有数字索引的数组的关联数组出现,这将不会被排序,因此如果您需要对其排序,可能需要使用asort()
。