根据字符串开头的连续符号数创建分层多维数组



我不确定标题是否正确,因为很难解释。我想根据每个数组的标签计数将一维数组转换为多维数组。

所以基本上我想要这个。

[
0 => "# Grandparent #1"
1 => "# Grandparent #2"
2 => "## Parent #2-1"
3 => "### Child #2-1-1"
4 => "## Parent #2-2"
5 => "### Child #2-2-1"
6 => "### Child #2-2-2"
7 => "## Parent #2-3"
8 => "## Parent #2-4"
9 => "# Grandparent #3"
10 => "## Parent #3-1"
]

像这样的

[
[
'name' => 'Grandparent #1'
],
[
'name' => 'Grandparent #2',
'children' => [
[
'name' => 'Parent #2-1',
'children' => [
[
'name' => 'Child #2-1-1',
]
]
],
[
'name' => 'Parent #2-2',
'children' => [
[
'name' => 'Child #2-2-1'
],
[
'name' => 'Child #2-2-2'
]
]
],
[
'name' => 'Parent #2-3',
],
[ 
'name' => 'Parent #2-4',
],
],
],
[
'name' 'Grandparent #3',
'children' => [
[
'name' => 'Parent #3-1'
]
]
]
]

我的代码:
数据集是可重复性最小的示例
在前一个之后还可以有无限量的#
第二个标签(#2-1-1(用于提供清晰性,而不是问题的一部分。

$array = [
"# Grandparent #1",
"# Grandparent #2",
"## Parent #2-1",
"### Child #2-1-1",
"## Parent #2-2",
"### Child #2-2-1",
"### Child #2-2-2",
"## Parent #2-3",
"## Parent #2-4",
"# Grandparent #3",
"## Parent #3-1",
];
function structure($lines, $target = 1) {
$data = [];
$parent = 0;
$i = 0;
foreach($lines as $line) {
$current = strlen(preg_split('/s+/', $line)[0]);
if ($current == $target) {
$parent = $i;
$data[$parent]['name'] = $line;
}
if ($current != $target) {
$data[$parent]['children'][] = $line;
}
$i++;
}
// I tried placing structure function here again but it gives me errors
// structure($data[$parent]['children'], $target + 1);
return $data;
}
$data = structure($array);

我已经让祖父母工作了,但我似乎无法让它完成其余的工作。我试着把循环放在一边,让它搜索其他孩子,但它只会无限运行。我不能把foreach放在foreach里面,等等,因为标签的数量可以是任何长度。

我没有太多时间研究这个,但这就是我想到的。。。

  1. 循环通过行数组
  2. 将哈希符号序列与成员名称分开
  3. 测量哈希符号字符串的长度,并将其与当前级别进行比较
  4. 对于";"父";在给定级别上,创建一个引用变量并将其推入输出数组(树(
  5. 每当你遇到一个新的";"父";在给定级别上,必须销毁旧引用并声明新引用
  6. 当需要递归时,只将直接子体传递到递归调用中
  7. 递归调用需要在循环结束时有条件地调用,以便处理未处理的子代

代码:(演示(

function recurse(array $lines, int $level = 1): array
{
$tree = [];
$directDescendants = [];
foreach ($lines as $line) {
[$hashes, $name] = explode(' ', $line, 2);
$depth = strlen($hashes);
if ($depth === $level) {
if ($directDescendants) {
$parent['children'] = recurse($directDescendants, $level + 1);
}
$directDescendants = [];      // reset collection of direct descendants
unset($parent);               // destroy reference
$parent = ['name' => $name];  // name the member
$tree[] = &$parent;           // push the reference variable into the tree
} elseif ($depth > $level) {
$directDescendants[] = $line; // collect only direct descendants of current level parent member
}
}
if ($directDescendants) {
$parent['children'] = recurse($directDescendants, $level + 1);
}
return $tree;
}
var_export(recurse($array));

最新更新