Skip to content

Other Tree Format

Rhilip edited this page Feb 24, 2025 · 3 revisions

By default, Call $fileTree = $torrent->getFileTree(?$sortType = TorrentFile::FILETREE_SORT_NORMAL); will return the array like:

[
    "torrentname" => [
        "directory" => [
            "filename2" => 2345
        ],
        "filename1" => 123
   ]
]

However, You can trans to other format by other code outsize the Bencode Library.

jsTree Format

Tree Format Example:

{
   "id": 0,
   "text": "title",
   "size": 0,
   "children": []
}

Example Javascript Transform Code:

function convertToTree(input) {
  function processEntry(key, value, parentId, indexInParent) {
    const id = parentId === null ? 
      `${indexInParent + 1}` : 
      `${parentId}-${indexInParent + 1}`;
    const node = { id, label: key };
    if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
      const children = [];
      let size = 0;
      let childIndex = 0;
      for (const [childKey, childValue] of Object.entries(value)) {
        const childNode = processEntry(childKey, childValue, id, childIndex);
        children.push(childNode);
        size += childNode.size;
        childIndex++;
      }
      node.children = children;
      node.size = size;
    } else {
      node.size = value;
    }
    return node;
  }

  return Object.entries(input).map(([key, value], index) => 
    processEntry(key, value, null, index)
  );
}

Example PHP Transform Code:

function convertToTree($input) {
    function processEntry($key, $value, $parentId, $indexInParent) {
        $id = $parentId === null ? 
            (string)($indexInParent + 1) : 
            $parentId . '-' . ($indexInParent + 1);
        $node = [
            'id' => $id,
            'label' => $key,
        ];
        if (is_array($value)) {
            $children = [];
            $size = 0;
            $childIndex = 0;
            foreach ($value as $childKey => $childValue) {
                $childNode = processEntry($childKey, $childValue, $id, $childIndex);
                $children[] = $childNode;
                $size += $childNode['size'];
                $childIndex++;
            }
            $node['children'] = $children;
            $node['size'] = $size;
        } else {
            $node['size'] = $value;
        }
        return $node;
    }

    $output = [];
    $index = 0;
    foreach ($input as $key => $value) {
        $output[] = processEntry($key, $value, null, $index);
        $index++;
    }
    return $output;
}

Clone this wiki locally