<?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.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.25, 8.4.1 - 8.4.12
- 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:
154.25 ms | 413 KiB | 5 Q