3v4l.org

run code in 300+ PHP versions simultaneously
<?php $input = [ ['pc', ['pc', null, null], 'id' => 1, 'pid' => 0], ['laptop', ['pc', 'laptop', null], 'id' => 2, 'pid' => 0], ['acc', ['pc', 'acc', null], 'id' => 3, 'pid' => 0], ['bags', ['pc', 'acc', 'bags'], 'id' => 4, 'pid' => 0], ['adapter', ['pc', 'acc', 'adapter'], 'id' => 5, 'pid' => 0], ['clothes', ['clothes', null, null], 'id' => 6, 'pid' => 0] ]; function fillParentIds(array $input): array { return array_values(array_reduce($input, static function ($entriesByPath, $entry) { $hierarchy = array_filter($entry[1]); $pathToParent = implode('/', array_slice($hierarchy, 0, -1)); $pathToEntry = implode('/', $hierarchy); $entry['pid'] = array_key_exists($pathToParent, $entriesByPath) ? $entriesByPath[$pathToParent]['id'] : $entry['id']; $entriesByPath[$pathToEntry] = $entry; return $entriesByPath; }, [])); } print_r(fillParentIds($input));

preferences:
24.75 ms | 402 KiB | 5 Q