3v4l.org

run code in 300+ PHP versions simultaneously
<?php $rows = [ ['name' => 'blah', 'path' => 'A'], ['name' => 'blah', 'path' => 'AA'], ['name' => 'blah', 'path' => 'AB'], ['name' => 'blah', 'path' => 'C'], ['name' => 'blah', 'path' => 'D'], ['name' => 'blah', 'path' => 'B'], ['name' => 'blah', 'path' => 'BA'], ['name' => 'blah', 'path' => 'BAA'], ['name' => 'blah', 'path' => 'CA'], ]; function rowsToTree(&$array, $parent = '') { $children = []; foreach ($array as $i => &$row) { if ($parent === substr($row['path'], 0, -1)) { $found = rowsToTree($array, $row['path']); if ($found) { $row['children'] = $found; if ($parent) { unset($array[$i]); } } if ($parent) { $children[] = $row; unset($array[$i]); } } } return $children; } rowsToTree($rows); var_export($rows);

preferences:
31.02 ms | 405 KiB | 5 Q