File "tree_view03.php"
Full Path: /home/analogde/www/php/FormData/uploads/2024_PHP_02_01_2025/tree_view03.php
File size: 2.53 KB
MIME-type: text/x-php
Charset: utf-8
<?php
// Exemple de données d'entrée
$filesArray = [
"fichiers" => [
"fichier1" => ["fichier2", "fichier3"],
"toto1" => ["toto2", "toto3", "toto4"],
]
];
// Fonction pour transformer le tableau en une structure d'arborescence
function buildTree($files) {
$result = [];
foreach ($files as $parent => $children) {
$childNodes = [];
foreach ($children as $child) {
$childNodes[] = ["name" => $child]; // Ajouter chaque enfant
}
$result[] = ["name" => $parent, "children" => $childNodes]; // Ajouter le parent avec ses enfants
}
return $result;
}
// Générer l'arborescence
$filesData = buildTree($filesArray['fichiers']);
// Convertir en JSON
$jsonData = json_encode($filesData);
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tree Viewer</title>
<style>
ul {
list-style-type: none;
padding-left: 20px;
}
.toggle {
cursor: pointer;
color: blue;
text-decoration: underline;
}
</style>
</head>
<body>
<h1>Arborescence des fichiers</h1>
<ul id="fileTree"></ul>
<script>
// Utiliser le JSON généré par PHP
const filesData = <?php echo $jsonData; ?>;
function createTree(files) {
const ul = document.createElement('ul');
files.forEach(file => {
const li = document.createElement('li');
const span = document.createElement('span');
span.classList.add('toggle');
span.textContent = file.name;
li.appendChild(span);
if (file.children) {
const childUl = createTree(file.children);
li.appendChild(childUl);
}
ul.appendChild(li);
});
return ul;
}
const fileTree = createTree(filesData);
document.getElementById('fileTree').appendChild(fileTree);
document.querySelectorAll('.toggle').forEach(item => {
item.addEventListener('click', event => {
const nextUl = item.nextElementSibling;
if (nextUl) {
nextUl.style.display = nextUl.style.display === 'none' || nextUl.style.display === '' ? 'block' : 'none';
}
});
});
// Initialiser l'affichage des sous-listes
/*
document.querySelectorAll('#fileTree ul').forEach(ul => {
ul.style.display = 'none'; // Par défaut, caché
});*/
</script>
</body>
</html>