<?php
function buildTree($data, $currentDepth = 0, $startIndex = 0) {
$tree = array();
foreach ($data as $i=>$c) {
if ($i < $startIndex) {
continue;
}
$depth = 0;
if (preg_match('/^([-]*)/', $c, $m)) {
$depth = strlen($m[1]);
}
if ($depth < $currentDepth) {
break;
} elseif ($depth != $currentDepth) {
continue;
}
$node = array('text' => preg_replace('/^[-]*/', '', $c));
$nodes = buildTree($data, $depth + 1, $i + 1);
if (count($nodes) > 0) {
$node['nodes'] = $nodes;
}
$tree[] = $node;
}
return $tree;
}
$categories = [
'Games',
'-Sports',
'--Footbal',
'--Basketball',
'-Action',
'--FPS',
'--RPG',
'-SIM',
];
echo json_encode( buildTree($categories), JSON_PRETTY_PRINT );