Skip to content

Instantly share code, notes, and snippets.

View Silloky's full-sized avatar

Silloky

View GitHub Profile
@Silloky
Silloky / getStructure.php
Created July 20, 2023 14:52
PHP : get recursive directory structure
<?php
function getContents($path) {
$contents = array_diff(scandir($path, SCANDIR_SORT_ASCENDING), array('..', '.')); // For Linux environments, excluded the .. and . from list
$filtered = array();
foreach ($contents as $item) {
$itemPath = $path . '/' . $item; // scan_dir() requires an entire path, not just the filename (unless you cd in the directory)
if (is_dir($itemPath)){ // only keeps the directories
$subarray = array('name' => "$item", 'children' => getContents($itemPath)); // saves the folder name as `name` property and the children recursively
array_push($filtered, $subarray);