【发布时间】:2018-09-27 13:27:40
【问题描述】:
我有一个低于 JSON 格式的数据。
$strTree = '{"id":"1","children":[{"id":"316","children":[{"id":"336","children":[{"id":"423"}]},{"id":"337","children":[{"id":"418"}]},{"id":"420"}]},{"id":"405"},{"id":"421"}]}';
现在我必须使用这些数据构建新数组来识别报告经理
$strTree = [
'316' => '1',
'405' => '1',
'421' => '1',
'336' => '316',
'337' => '316',
'420' => '316',
'418' => '337',
'423' => '336',
]
这里我已经尝试过,但没有找到获得预期结果的解决方案
$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);
【问题讨论】:
-
$arr = json_decode($strTree, true);会给你一个数组,如果你不喜欢使用对象。 -
@RiggsFolly 我已经将该 JSON 转换为一个数组,但我无法从转换后的数组中准备预期的数组。