<?php
function replaceParent(&$array, $parent = null) {
foreach ($array as &$item) {
if ($item['id'] == $parent) {
if ($item['parent']) {
return replaceParent($array, $item['parent']);
} else {
return $item['id'];
}
} elseif ($item['parent']) {
$item['parent'] = replaceParent($array, $item['parent']);
}
}
}
$array = [
'0' => [
'id' => 1,
'parent' => 0,
'name' => 'root 0'
],
'1' => [
'id' => 2,
'parent' => 1,
'name' => 'root 1'
],
'2' => [
'id' => 3,
'parent' => 2,
'name' => 'root 2'
],
'3' => [
'id' => 4,
'parent' => 3,
'name' => 'root 3'
],
'4' => [
'id' => 5,
'parent' => 3,
'name' => 'root 4'
],
'5' => [
'id' => 6,
'parent' => 2,
'name' => 'root 2'
]
];
replaceParent($array);
var_export($array);
- Output for 7.1.25 - 7.1.32, 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.19, 8.3.0 - 8.3.4, 8.3.6 - 8.3.7
- array (
0 =>
array (
'id' => 1,
'parent' => 0,
'name' => 'root 0',
),
1 =>
array (
'id' => 2,
'parent' => 1,
'name' => 'root 1',
),
2 =>
array (
'id' => 3,
'parent' => 1,
'name' => 'root 2',
),
3 =>
array (
'id' => 4,
'parent' => 1,
'name' => 'root 3',
),
4 =>
array (
'id' => 5,
'parent' => 1,
'name' => 'root 4',
),
5 =>
array (
'id' => 6,
'parent' => 1,
'name' => 'root 2',
),
)
- 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 (
'id' => 1,
'parent' => 0,
'name' => 'root 0',
),
1 =>
array (
'id' => 2,
'parent' => 1,
'name' => 'root 1',
),
2 =>
array (
'id' => 3,
'parent' => 1,
'name' => 'root 2',
),
3 =>
array (
'id' => 4,
'parent' => 1,
'name' => 'root 3',
),
4 =>
array (
'id' => 5,
'parent' => 1,
'name' => 'root 4',
),
5 =>
array (
'id' => 6,
'parent' => 1,
'name' => 'root 2',
),
)
preferences:
209.14 ms | 403 KiB | 178 Q