代码之家  ›  专栏  ›  技术社区  ›  Gajanan Kolpuke

如何将层次结构从数组转换为单个数组

  •  1
  • Gajanan Kolpuke  · 技术社区  · 8 年前

    我有一个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);
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Ezequiel De Luca    8 年前

    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"
    }