PHP. Как сформировать динамический многомерный массив?
Без использования ссылок дерево собирается так:<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('xdebug.var_display_max_depth', -1);

$items = [
    ['id' => 1, 'name' => 'A',          'parent' => 0],
    ['id' => 2, 'name' => 'A-1',        'parent' => 1],
    ['id' => 3, 'name' => 'A-1-1',      'parent' => 2],
    ['id' => 5, 'name' => 'A-1-1-2',    'parent' => 3],
    ['id' => 6, 'name' => 'A-2',        'parent' => 1],
    ['id' => 7, 'name' => 'A-2-2-1',    'parent' => 6],
    ['id' => 4, 'name' => 'A-1-1-1',    'parent' => 3],
    ['id' => 8, 'name' => 'A-2-2-2',    'parent' => 6],
    ['id' => 9, 'name' => 'A-2-2-1-1',  'parent' => 7],
    ['id' => 10,'name' => 'B',          'parent' => 0],
];

function buildTree(array $items, $parent = 0)
{
    $tree = array();
    foreach ($items as $item) {
        if ($item['parent'] === $parent) {
            $children = buildTree($items, $item['id']);
            if ($children) {
                $item['children'] = $children;
            }
            $tree[] = $item;
        }
    }

    return $tree;
}

function getList($items = [])
{
    $html = '';
    foreach ($items as $item) {
        $html .= vsprintf('<ul><li><span>%s</span>%s</li></ul>', [
            $item['name'],
            empty($item['children']) ? '' : getList($item['children'])
        ]);
    }

    return $html;
}

$tree = buildTree($items);
$list = getList($tree);

echo "<pre>";
echo $list;
var_dump($tree);
echo "</pre>";
exit("File: " . __FILE__ . " Line: " . __LINE__);
Примерно так:$sql = 'SELECT * FROM `categories`';
$stmt = DBH::PDO()->query($sql)->execute();
$data = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC){
  $data[$row['parent']][$row['id']] = $row;
}