【问题标题】:How to convert Hierarchical from array to single array如何将层次结构从数组转换为单个数组
【发布时间】: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 转换为一个数组,但我无法从转换后的数组中准备预期的数组。

标签: php arrays recursion


【解决方案1】:

Gerber,要解决这个问题,您可以使用递归函数来“展平”分层数组:

function flattenHierarchicalArray($inputArray, $parentId = null)
{
    $flattenedData = [];
    if (!empty($inputArray['children'])) {
        foreach ($inputArray['children'] as $child) {
            $flattenedData += flattenHierarchicalArray($child, $inputArray['id']);
        }
    }

    if (!is_null($parentId)) {
        $flattenedData[$inputArray['id']] = $parentId;
    }

    return $flattenedData;
}

你应该这样调用函数:

flattenHierarchicalArray($data)

其中 $data 是从您的 JSON 示例解码的分层数组。输出:

array(8) {
  [423]=>
  string(3) "336"
  [336]=>
  string(3) "316"
  [418]=>
  string(3) "337"
  [337]=>
  string(3) "316"
  [420]=>
  string(3) "316"
  [316]=>
  string(1) "1"
  [405]=>
  string(1) "1"
  [421]=>
  string(1) "1"
}

注意:此函数不会保持您预期输出的顺序,我认为这根本不重要。

【讨论】:

  • 我刚刚将 $inputArray [ $inputArray = (array) $inputArray ] 类型修改为数组,它对我有用。非常感谢。
  • @GajananKolpuke 不客气。为了避免 $inputArray 变量的强制转换,您可以将 true 作为 json_decode 的第二个参数传递。使用该参数 json_decode 返回关联数组而不是 PHP StdObject。
猜你喜欢
  • 2019-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多