I have a data in below JSON format.
$strTree = '{"id":"1","children":[{"id":"316","children":[{"id":"336","children":[{"id":"423"}]},{"id":"337","children":[{"id":"418"}]},{"id":"420"}]},{"id":"405"},{"id":"421"}]}';
And Now I have to build new array using this data for identifying reporting manager
$strTree = [
'316' => '1',
'405' => '1',
'421' => '1',
'336' => '316',
'337' => '316',
'420' => '316',
'418' => '337',
'423' => '336',
]
Here What I have tried, but didn't find out the solution to get the expected result
$strTree = '{
"id": "1",
"children": [{
"id": "316",
"children": [{
"id": "336",
"children": [{"id": "423"}]
},
{
"id": "337",
"children": [{"id": "418"}]
}, {"id": "420"}
]
},
{"id": "405"},
{"id": "421"}
]}';
$arr = (array) json_decode($strTree);
$arrHierarchicalEmpDetails = buildResultedArray($arr, 1);
function buildResultedArray( $elements, $parentId = 0) {
$branch = [];
$elements = (array) $elements;
foreach ($elements as $element) {
$element = (array) $element;
$intID = $element['id'];
$branch[ $intID ] = $parentId;
if (!empty( $element['children'])) {
buildTree( $element['children'], $element['id']);
}
}
return $branch;
}
echo '<pre>'; print_r($arrHierarchicalEmpDetails);