简体   繁体   English

将键值对的PHP数组转换为分层嵌套树结构

[英]Converting a PHP array of key value pairs to a hierarchical nested tree structure

I have a situation where I have an array structure that consists of about 6,000 key/value pairs. 我有一种情况,我有一个由大约6,000个键/值对组成的数组结构。

The array is in a structure like: 该数组的结构如下:

Array
(
[0] => Array
    (
        [parent] => parentA
        [name] => child1
    )

[1] => Array
    (
        [parent] => parentB
        [name] => childC
    )

[2] => Array
    (
        [parent] => parentA
        [name] => child2
    )

[3] => Array
    (
        [parent] => parentC
        [name] => child3
    )
[4] => Array
    (
        [parent] => child1
        [name] => child4
    )

[5] => Array
    (
        [parent] => child4
        [name] => child5
    )

From that data source I am trying to massage the output into 从那个数据源我试图按下输出

A) An array that I can use in later functionality A)我可以在以后的功能中使用的数组
B) A table display where each row will be one full chain, and each column will be a level deeper. B)一个表格显示,其中每一行将是一个完整的链,每列将更深。 Essentially if you think of page navigation, this is a bread crumb display where each node would be in the next column. 基本上,如果您考虑页面导航,这是一个面包屑显示,其中每个节点都在下一列中。

I have been playing with a few approaches here 我这里一直在玩几种方法

1) Using the recursive function at this stack overflow question: https://stackoverflow.com/a/2915920/997226 , however I have not been able to modify this to work with my data where the parent can be the same. 1)在此堆栈溢出问题中使用递归函数: https//stackoverflow.com/a/2915920/997226 ,但是我无法修改它以使用父数据可以相同的数据。 In their example of $tree, the left hand (key) value is always unique. 在$ tree的示例中,左手(键)值始终是唯一的。

I understand in their example their key is the child, and the value (right hand side) is the parent, however I still can not get this to work for me as in my data there are multiples of the same item on both the parent side and the child side. 我在他们的例子中理解他们的关键是孩子,价值(右手边)是父母,但是我仍然无法让这个为我工作,因为在我的数据中父母身边有相同项目的倍数和孩子一边。 (Think complex relationships where an article can be contained within multiple parent categories. (想想一下文章可以包含在多个父类别中的复杂关系。

2) I have tried starting to create a "base array" of unique parent elements, and then creating a recursive function to do a search on the "original key value array" but this didn't quite work either. 2)我已经尝试开始创建一个独特的父元素的“基础数组”,然后创建一个递归函数来搜索“原始键值数组”,但这也不是很有效。

3) I tried saving the data in a database as I'm pretty familiar with using left/right values for accessing/manipulating data as a nested set, but I'm trying to avoid having to have everything INSERT/SELECT from a database. 3)我尝试将数据保存在数据库中,因为我非常熟悉使用左/右值来访问/操作数据作为嵌套集,但我试图避免必须从数据库中获取所有INSERT / SELECT。

4) I tried working with the various PHP Iterators classes as I have used these successfully for working with the file system and building file/directory listings, so I've been playing with RecursiveArrayIterator / ParentIterator/ArrayIterator, but can't seem to figure out the proper syntax to use. 4)我尝试使用各种PHP Iterators类,因为我已成功使用它们来处理文件系统和构建文件/目录列表,所以我一直在玩RecursiveArrayIterator / ParentIterator / ArrayIterator,但似乎无法想象使用正确的语法。

I understand that recursing may not be as efficient as using references for a data set of this size, however it seems like it provides the most flexibility, I just can't seem to get it to iterate recursively correctly. 我知道递归可能不如使用这个大小的数据集的引用那么有效,但是它似乎提供了最大的灵活性,我似乎无法让它以递归方式正确迭代。

Beyond, this specific question, I'm also trying to better understand the algorithm nature of programmatic recursion. 除此之外,这个具体问题,我也试图更好地理解程序递归的算法性质。

The more I read through other people's code examples that are trying to do something similar, but with a different data structure I just become more confused. 我通过其他人尝试做类似事情的代码示例阅读的越多,但是使用不同的数据结构我会变得更加困惑。

If anyone could help point me in the right direction it would be appreciated. 如果有人能帮助我指出正确的方向,我们将不胜感激。

Clarification Notes 澄清说明

  1. There will be multiple levels. 将有多个级别。
  2. It has been pointed out that the data structure can be thought of as a Directed acyclic graph and that makes complete sense. 已经指出,数据结构可以被认为是有向无环图并且完全有意义。

** Update #2 - I've redesigned using referencing (not recursion). **更新#2 - 我使用引用(不是递归)重新设计。 This requires only a single pass through the data. 这只需要一次通过数据。 Every parent or child is added as a top level item to an array ($a in this case) if it does not already exist. 每个父级或子级都作为顶级项添加到数组(在本例中为$ a)(如果它尚不存在)。 The key of this top level item is the name of the parent or child. 此顶级项的键是父级或子级的名称。 The value is an array which contains references to its children's top level item. 该值是一个数组,其中包含对其子级顶级项的引用。 In addition, a second array ($p) is created with only references to the parents in the first array ($a). 此外,创建第二个数组($ p),仅引用第一个数组中的父项($ a)。 In a single pass which is very quick, all the relationships are discovered. 在一次非常快速的通过中,发现了所有的关系。

The Code (for update #2): 守则(更新#2):

<?php
$tree_base = array(
    array('parent' => 'parentA','name' => 'child1'),
    array('parent' => 'parentB','name' => 'childC'),
    array('parent' => 'parentA','name' => 'child2'),
    array('parent' => 'parentC','name' => 'child3'),
    array('parent' => 'child1','name' => 'child4'),
    array( 'parent' => 'child4', 'name' => 'child5'),
    array( 'parent' => 'DataSelect', 'name' => 'getBaseUri'),
    array( 'parent' => 'getBaseUri', 'name' => 'getKbBaseURI')
    );

    $tree = parseTree($tree_base);
    echo '<pre>'.print_r($tree, TRUE).'</pre>';
    showresults($tree);

function parseTree($tree){
    $a = array();
    foreach ($tree as $item){
        if (!isset($a[$item['name']])){
            // add child to array of all elements
            $a[$item['name']] = array();
        }
        if (!isset($a[$item['parent']])){
            // add parent to array of all elements
            $a[$item['parent']] = array();

            // add reference to master list of parents
            $p[$item['parent']] = &$a[$item['parent']];
        }
        if (!isset($a[$item['parent']][$item['name']])){
            // add reference to child for this parent
            $a[$item['parent']][$item['name']] = &$a[$item['name']];
        }   
    }
    return $p;
}

function showresults($tree, &$loop = array()){
        if (is_array($tree) & count($tree) > 0){       
                echo "<table>";
                echo "<tr>";
                foreach ($tree as $key => $children){
                    // prevent endless recursion
                    if (!array_key_exists($key, $loop)){
                        $loop[$key] = null;
                        echo "<tr>";
                        echo "<td style='border:1px solid'>";
                        echo $key;
                        echo "<td style='border:1px solid'>";
                        showresults($children, $loop);
                        echo "</td>";
                        echo "</td>";
                        echo "</tr>";
                    }
                }
                echo "</tr>";
                echo "</table>";
        }
}

?>

The output (for update #2): 输出(对于更新#2):

Array
(
    [parentA] => Array
        (
            [child1] => Array
                (
                    [child4] => Array
                        (
                            [child5] => Array
                                (
                                )

                        )

                )

            [child2] => Array
                (
                )

        )

    [parentB] => Array
        (
            [childC] => Array
                (
                )

        )

    [parentC] => Array
        (
            [child3] => Array
                (
                )

        )

    [DataSelect] => Array
        (
            [getBaseUri] => Array
                (
                    [getKbBaseURI] => Array
                        (
                        )

                )

        )

)

在此输入图像描述

**Update #1 - I've fixed code to show multi-level children (and your new example array structure). **更新#1 - 我已修复代码以显示多级子级(以及您的新示例数组结构)。 To keep it clean, I am only using the key of the resulting array elements to store the name of parent and child. 为了保持干净,我只使用生成的数组元素的键来存储父级和子级的名称。 The table output becomes more visually complicated. 表输出变得更加复杂。 I've used one row for each parent / child group with the first column for the parent and second column for its children. 我为每个父/子组使用了一行,其中第一列为父级,第二列为其子级。 This is also recursive so that the column containing the children can show its children (if any) in a new table of the same format (easier viewed than explained). 这也是递归的,因此包含子项的列可以在相同格式的新表中显示其子项(如果有)(查看比查找更容易)。

The output (for update #1): 输出(对于更新#1):

 Array
(
    [parentA] => Array
        (
            [child1] => Array
                (
                    [child4] => Array
                        (
                            [child5] => 
                        )

                )

            [child2] => 
        )

    [parentB] => Array
        (
            [childC] => 
        )

    [parentC] => Array
        (
            [child3] => 
        )

)

在此输入图像描述

The code (for update #1): 代码(用于更新#1):

<?php
$array = array(
    array('parent' => 'parentA',
                    'name' => 'child1'),
    array('parent' => 'parentB',
                    'name' => 'childC'),
    array('parent' => 'parentA',
                    'name' => 'child2'),
    array('parent' => 'parentC',
                    'name' => 'child3'),
    array('parent' => 'child1',
                    'name' => 'child4'),
    array( 'parent' => 'child4',
                    'name' => 'child5')
    );

    // parse array into a hierarchical tree structure
    $tree = parseTree($array);

    // Show results
    echo '<pre>';
    print_r($tree);
    echo '</pre>';  
    echo "<br>Table Format:";

    showresults($tree);

    function parseTree(& $tree, $root = null) {
        $return = null;
        // Traverse the tree and search for children of current parent
      foreach ($tree as $key=> $item){
      // A child is found
            if ($item['parent'] == $root){
                // append child into array of children & recurse for children of children
                $return[$item['name']] = parseTree($tree, $item['name']);
                // delete child so won't include again
                unset ($tree[$key]);
            }
            elseif ($root == null) {
                // top level parent - add to array 
                $return[$item['parent']] = parseTree($tree, $item['parent']);
                // delete child so won't include again
                unset ($tree[$key]);
            }
        }
        return $return;
    }

    function showresults($tree){

        if (is_array($tree)){       
            echo "<table>";
            echo "<tr>";

            foreach ($tree as $key => $children){
                echo "<tr>";

                echo "<td style='border:1px solid'>";
                echo $key;

                echo "<td style='border:1px solid'>";
                showresults($children, true);
                echo "</td>";

                echo "</td>";

                echo "</tr>";
            }

            echo "</tr>";
            echo "</table>";
        }
    }

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM