我的SQL查询使我得到这样的结果:
Maths
Maths|Algebre
Maths|Algebre|Algebre 1
Maths|Algebre|Algebre 2
Maths|Algebre|Algebre 3
Maths|Analyse
Maths|Analyse|Analyse 1
Maths|Analyse|Analyse 2
Maths|Probabilité
physics
我尝试了许多不成功的方法来使用这些字符串来最终在html中创建嵌套列表。
我想将它们保存为这样的嵌套数组:
$stack= array(
"maths" => array(
"Algebre" => array( "Algebre 1" ,"Algebre 2"),
"Analyse" => array("Analyse 1","Analyse 2"),
"Proba"
),
"Physics"
) ;
然后我会做这样的事情:
function print_list($array){
echo "<ul>" ;
foreach($array as $key => $item) {
if (is_string($key)) echo "<li> $key" ;
if (is_array($item)) print_list($item) ;
else echo "<li> $item" ;
echo "</li>" ;
}
echo "</ul>" ;
}
print_list($stack);
这是可能的实现:
cleanupLines
从原始字符串中删除所有“无用的”行(它将仅保留带有叶子的行),lineToArray
取线段(除以|
后,然后递归调用自身以生成给定线的数组,]array_merge_recursive
将所有数组合并为一个。代码:
function cleanupLines(array $lines): array
{
foreach ($lines as $index => $line) {
if ($index > 0 && strpos($line, $lines[$index - 1]) === 0) {
unset($lines[$index - 1]);
}
}
return $lines;
}
function lineToArray(array $lineParts): array
{
if (count($lineParts) > 1) {
return [$lineParts[0] => lineToArray(array_slice($lineParts, 1))];
}
return $lineParts;
}
$lines = preg_split('/\r?\n/', $input);
$lines = cleanupLines($lines);
$result = array_reduce($lines, static function (array $result, string $line): array {
$lineParts = explode('|', $line);
$arrayPart = lineToArray($lineParts);
return array_merge_recursive($result, $arrayPart);
}, []);
print_r($result);