3v4l.org

run code in 300+ PHP versions simultaneously
<?php $list = [ [ 'name' => 'blah', 'path' => 'A' ], [ 'name' => 'blah', 'path' => 'AA' ], [ 'name' => 'blah', 'path' => 'AB' ], [ 'name' => 'blah', 'path' => 'B' ], [ 'name' => 'blah', 'path' => 'BA' ], [ 'name' => 'blah', 'path' => 'BAA' ], ]; $result = array_reduce($list, function ($a, $c) { $l = substr($c['path'], 0, 1); isset($a[$l]) ? $a[$l]['children'][] = $c : $a[$l] = [ 'name' => $c['name'], 'path' => $c['path'], 'children' => [] ]; return $a; }, []); // to remove the letter keys, uncomment the next line // $result = array_values($result); var_export($result);

preferences:
27.88 ms | 406 KiB | 5 Q