【发布时间】:2020-12-31 07:50:10
【问题描述】:
我不确定标题是否正确,因为很难解释。 我想根据每个数组的标签计数将一维数组转换为多维数组。
所以基本上我想要这个。
[
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 中等等,因为标签的数量可以是任意长度。
【问题讨论】:
标签: php arrays recursion hierarchical-data