PHP中将缩进文本转换为多维数组的问题求助
PHP:将按3空格层级缩进的文本转换为多维数组
问题核心
需要将首行无缩进、后续以3个空格为一个层级的文本,转换为包含value和children字段的多维数组,此前的实现因层级判断逻辑错误导致子节点无法正确挂载。
修正后的实现函数
function convertIndentedTextToArray($text) { $lines = explode("\n", $text); $result = []; $stack = []; foreach ($lines as $line) { // 跳过空行 $trimmedLine = trim($line); if (empty($trimmedLine)) continue; // 统计总缩进空格数 $indent = strlen($line) - strlen($trimmedLine); // 计算层级:3个空格为一级 $level = floor($indent / 3); $node = ['value' => $trimmedLine, 'children' => []]; // 调整栈的深度,匹配当前层级 while ($level < count($stack)) { array_pop($stack); } // 将节点挂载到对应父节点或根数组 if (empty($stack)) { $result[] = &$node; } else { $parent = &$stack[count($stack) - 1]; $parent['children'][] = &$node; } // 将当前节点加入栈 $stack[] = &$node; // 解除引用避免后续错误 unset($node, $parent); } return $result; }
关键修改说明
- 层级计算逻辑:将原代码中按单个空格计数的
$indent,改为按3个空格为单位计算层级$level,这是解决子节点挂载错误的核心。 - 空行处理:跳过空行,避免生成无效的空节点。
- 引用解除:在每次循环末尾解除变量引用,防止后续循环中意外修改已存入数组的节点。
测试验证
测试输入(符合3空格层级格式)
$input = "Hello world I am good Hey it's wonderful This is good time I love the way you are Hey again I am on root";
调用函数并输出
$result = convertIndentedTextToArray($input); echo "<pre>"; print_r($result); echo "</pre>";
输出结果(符合预期结构)
Array ( [0] => Array ( [value] => Hello world I am good [children] => Array ( [0] => Array ( [value] => Hey it's wonderful [children] => Array ( ) ) [1] => Array ( [value] => This is good time [children] => Array ( [0] => Array ( [value] => I love the way you are [children] => Array ( ) ) ) ) ) ) [1] => Array ( [value] => Hey again I am on root [children] => Array ( ) ) )
原代码问题分析
- 第一个实现函数错误地将单个空格作为层级判断依据,而非需求中的3个空格,导致栈的深度计算完全错误,子节点无法挂载到正确的父节点下,最终出现
children数组为空的情况。 - 第二个实现代码采用硬编码层级(3、6、9)的方式,扩展性差,且未处理层级间的正确关联逻辑,同样无法生成符合要求的多维数组结构。
内容的提问来源于stack exchange,提问作者Narendra Sharma
相关产品推荐
相关产品推荐

