如何从string中递归构建json

I am trying to map a JSON from a string There is my string

files/a/b.txt

and I want to map a JSON like this

{
    "name" => "files",
    "path" => "files",
    "type" => "folder",
    "items" => [{
        "name" => "a",
        "path" => "files/a",
        "type" => "folder",
        "items" => [{
            "name" => "b.txt",
            "path" => "files/a/b.txt",
            "type" => "file",
        }]
    }]
}

Here I showed one subfolder but it can be infinite subfolders. Any help would be appreciated.Thanks.

UPDATE: That's what I have right now

$str = "files/a/b.txt";
$path = explode("/",$str);
$num = count($path);
$num = --$num;
$files = array();
if($num > 2) {
    foreach ($path as $keys => $value) {
        if($keys > 1 && $keys < $num) {
            $files[] = array(
            "name" => $value,
            "type" => "folder",
            "path" => $path[0]."/".$path[1]."/".$value,
            "items" => 
            );
        }
    }
}else{
    $files[] = array(
    "name" => $path[2],
    "type" => "file",
    "path" => $path[0]."/".$path[1]."/".$path[],
    "size" => filesize($path[0]."/".$path[1]."/".$path[])
    );
}
echo json_encode($files);

But I don't know how to write the items part.This code only works for one subfolder and still cannot include the file in the folder items.

Note: Consider that the path doesn't necessarily exist.

I don`t know how to do it in php,but in javascript it will be like this:

function myFunction(myString) 
{
    var object={};
    var path="";
    var array=myString.split("/"); 
    var items=[];
    if(array.length==1)
    {
        object={
                "name":array[0],
                "path":array[0],
                "type":"file"
            }
    } else{
        var path= array[0];
        var object={
                "name":array[0],
                "path":path,
                "type":"folder"
        }
        array.splice(0,1);
        object.items=[recursiveCall(array,path)]
    }
}

function recursiveCall(array,path){
            if(array.length==1){
                return {
                        "name":array[0],
                        "path":path+"/"+array[0],
                        "type":"file"
                    }

            }else{
                path=path+"/"+array[0];
                var obj={
                        "name":array[0],
                        "path":path,
                        "type":"folder"
                }
                array.splice(0,1);//remove first element
                obj.items=[recursiveCall(array,path)]
                return obj;
            }
         }