<?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));
- Output for 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.4, 8.3.6
- Array
(
[0] => Array
(
[0] => pc
[1] => Array
(
[0] => pc
[1] =>
[2] =>
)
[id] => 1
[pid] => 1
)
[1] => Array
(
[0] => laptop
[1] => Array
(
[0] => pc
[1] => laptop
[2] =>
)
[id] => 2
[pid] => 1
)
[2] => Array
(
[0] => acc
[1] => Array
(
[0] => pc
[1] => acc
[2] =>
)
[id] => 3
[pid] => 1
)
[3] => Array
(
[0] => bags
[1] => Array
(
[0] => pc
[1] => acc
[2] => bags
)
[id] => 4
[pid] => 3
)
[4] => Array
(
[0] => adapter
[1] => Array
(
[0] => pc
[1] => acc
[2] => adapter
)
[id] => 5
[pid] => 3
)
[5] => Array
(
[0] => clothes
[1] => Array
(
[0] => clothes
[1] =>
[2] =>
)
[id] => 6
[pid] => 6
)
)
- Output for 8.3.5
- Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
Array
(
[0] => Array
(
[0] => pc
[1] => Array
(
[0] => pc
[1] =>
[2] =>
)
[id] => 1
[pid] => 1
)
[1] => Array
(
[0] => laptop
[1] => Array
(
[0] => pc
[1] => laptop
[2] =>
)
[id] => 2
[pid] => 1
)
[2] => Array
(
[0] => acc
[1] => Array
(
[0] => pc
[1] => acc
[2] =>
)
[id] => 3
[pid] => 1
)
[3] => Array
(
[0] => bags
[1] => Array
(
[0] => pc
[1] => acc
[2] => bags
)
[id] => 4
[pid] => 3
)
[4] => Array
(
[0] => adapter
[1] => Array
(
[0] => pc
[1] => acc
[2] => adapter
)
[id] => 5
[pid] => 3
)
[5] => Array
(
[0] => clothes
[1] => Array
(
[0] => clothes
[1] =>
[2] =>
)
[id] => 6
[pid] => 6
)
)
preferences:
167.86 ms | 405 KiB | 175 Q