<?php
$input = <<<STR
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
STR;
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);
- Output for 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.4, 8.3.6
- Array
(
[Maths] => Array
(
[Algebre] => Array
(
[0] => Algebre 1
[1] => Algebre 2
[2] => Algebre 3
)
[Analyse] => Array
(
[0] => Analyse 1
[1] => Analyse 2
)
[0] => Probabilité
)
[0] => physics
)
- Output for 8.3.5
- Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
Array
(
[Maths] => Array
(
[Algebre] => Array
(
[0] => Algebre 1
[1] => Algebre 2
[2] => Algebre 3
)
[Analyse] => Array
(
[0] => Analyse 1
[1] => Analyse 2
)
[0] => Probabilité
)
[0] => physics
)
preferences:
178.21 ms | 403 KiB | 181 Q