Turn into ul

2

Hello, how are you?

asked by anonymous 06.05.2018 / 22:47

1 answer

4

There are several ways to do this. I created this example more simply, but I could have created a recursive function, for example. I did more for the challenge. =)

This is the texto.txt file that will be read with file_get_contents("texto.txt")

José
    Dados
        Idade: 30
        Estado Civil: Solteiro
    Hobbies
        Tocar violão
            Rock
            Blues
        Ler
        Viajem
            Praia

However, I did a test using string, and it reads normally, like this:

$string = "José
    Dados
        Idade: 30
        Estado Civil: Solteiro
    Hobbies
        Tocar violão
            Rock
            Blues
        Ler
        Viajem
            Praia";

No more ... follow the commented code:

$string =  file_get_contents("texto.txt"); // pega o conteudo
$string = explode("\n", $string); // separa as linhas
$array = array();

// cria o array com os níveis com contagem da tabulação
foreach($string as $linha){
    $num_spaces = substr_count($linha, " ");
    $tabs_count = floor($num_spaces / 4); // quantidade de tabulação
    $array[] = array( $tabs_count => $linha );
}

// mostra o menu
echo "<ul>";
for($x = 0; $x < count($array); $x++){
    $menu = $array[$x];
    foreach($menu as $key => $val){
        $chave = $key;
        $valor = $val;
    }
    if(isset($array[$x + 1])){
        $next = $array[$x + 1];
        foreach($next as $key => $val){
        $nextChave = $key;
        }
        if ($nextChave > $chave){
            echo "<li>".trim($valor);
            echo "<ul>";
        } else {
            if($nextChave == $chave){
                echo "<li>".trim($valor)."</li>";
            } else {
                echo "<li>".trim($valor)."</li></ul>";
            }
        }
    } else {
        echo "<li>".trim($valor)."</li>";
    }
}
echo "</ul>";
    
07.05.2018 / 01:20