$files = [
0 => "bbc",
1 => "bbc/images",
2 => "bbc/images/1",
3 => "bbc/videos",
4 => "bbc/videos/10",
5 => "cnn",
6 => "cnn/images",
7 => "cnn/images/2",
8 => "cnn/videos",
9 => "cnn/videos/20",
10 => "public",
];
$out = [];
class Tree
{
private $rel = "";
function clean()
{
$this->rel = "";
}
function makeit( &$buffer, $files, $rel )
{
$this->rel .= $rel . "/";
$files = explode( "/", $files );
if( $files == [] )
{
return $this;
}
$file = $files [ 0 ];
if( !isset( $buffer [ $file ] ))
{
$buffer[ $file ] = [
"name" => $file,
"relativepath" => $this->rel,
"children" => [],
];
if( count( $files) < 2 )
{
return $this;
}
$this->makeit( $buffer[ $file ]["children"], implode( "/", array_slice( $files, 1 ) ), $file);
}else {
$this->makeit( $buffer[ $file ]["children"], implode( "/", array_slice( $files, 1 ) ), $file);
}
return $this;
}
}
$tree = new Tree();
foreach( $files as $file )
{
$tree->makeit( $out, $file, "/nezar" )->clean();
}
$buffer = [];
foreach( $out as $o )
{
$buffer[] = $o;
}
echo json_encode( $buffer );
Created
August 18, 2019 12:41
-
-
Save nezarfadle/2fd066f0044f968ced790cf4f8d5c336 to your computer and use it in GitHub Desktop.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment