PHP分层数组 - 父母和孩子

时间:2012-12-14 11:19:29

标签: php arrays loops recursion parent-child

我将PHP和mySQL与Idiorm一起使用。这可能不相关。

我的PHP数组

  • 这是父母与孩子之间的关系。
  • 0是根父母。
  • 示例:根父0具有子33,其具有子27 孩子71。

如果需要解决问题,可以更改此数组结构。

array (
  33 => 
    array (
      0 => '27',
      1 => '41',
  ),
  27 => 
    array (
      0 => '64',
      1 => '71',
  ),
  0 => 
    array (
      0 => '28',
      1 => '29',
      2 => '33',
  ),
)

我的分层结果

像这样的东西,但作为一个数组...

  0 => 
      28
      29
      33
         27 =>
               64
               71
         41

信息

  • 深度未知,可以无限制。我试过foreach,但可能不是那样。

我自己的想法

  • 一些递归函数?
  • 有些循环?

我尝试了以上两种情况,只是弄得一团糟。这很简单。

5 个答案:

答案 0 :(得分:43)

@deceze的建议奏效了。但是输入数组需要改变一点,就像这样......

$rows = array(
    array(
        'id' => 33,
        'parent_id' => 0,
    ),
    array(
        'id' => 34,
        'parent_id' => 0,
    ),
    array(
        'id' => 27,
        'parent_id' => 33,
    ),
    array(
        'id' => 17,
        'parent_id' => 27,
    ),
);

来自https://stackoverflow.com/a/8587437/476

function buildTree(array $elements, $parentId = 0) {
    $branch = array();

    foreach ($elements as $element) {
        if ($element['parent_id'] == $parentId) {
            $children = buildTree($elements, $element['id']);
            if ($children) {
                $element['children'] = $children;
            }
            $branch[] = $element;
        }
    }

    return $branch;
}

$tree = buildTree($rows);

print_r( $tree );

答案 1 :(得分:5)

我添加了@JensTörnell的答案,以便为parent_id的列名,子数组键名以及id的列名定义选项。

/**
 * function buildTree
 * @param array $elements
 * @param array $options['parent_id_column_name', 'children_key_name', 'id_column_name'] 
 * @param int $parentId
 * @return array
 */
function buildTree(array $elements, $options = [
    'parent_id_column_name' => 'parent_id',
    'children_key_name' => 'children',
    'id_column_name' => 'id'], $parentId = 0)
    {
    $branch = array();
    foreach ($elements as $element) {
        if ($element[$options['parent_id_column_name']] == $parentId) {
            $children = buildTree($elements, $options, $element[$options['id_column_name']]);
            if ($children) {
                $element[$options['children_key_name']] = $children;
            }
            $branch[] = $element;
        }
    }
    return $branch;
}

由于功能完全通用,我设法在大多数项目中使用上述功能。

答案 2 :(得分:3)

来自@JensTörnell的很好的回答,只是想添加一点改进,如果你的parent_id和id实际上是字符串而不是数字,那么上面的方法将失败,并且在创建子数组之后,它将再次创建这些子数组作为单独的个体阵列。为了解决这个问题,你应该进行三次相等的检查,并通过比较来告诉变量的数据类型,即(字符串)。

对于基于字符串的Id和数组中的Parent_id

function buildTree(array $elements, $parentId = 0) {
    $branch = array();

    foreach ($elements as $element) {
        if ((string)$element['parent_id']  === (string)$parentId) {
            $children = buildTree($elements, $element['id']);
            if ($children) {
                $element['children'] = $children;
            }
            $branch[] = $element;
        }
    }

    return $branch;
}

另外,如果有人愿意,他可以添加第三个参数来动态指定变量的数据类型,即function buildTree(array $elements, $parentId = 0, $datatype='string')但是你必须承担任何其他错误。

希望它会帮助别人!

答案 3 :(得分:0)

public function createTree (&$list, $parentId = null) {
    $tree = array();
    foreach ($list as $key => $eachNode) {
        if ($eachNode['parentId'] == $parentId) {
            $eachNode['children'] = $this->createTree ($list,$eachNode['id']);
            $tree[] = $eachNode;
            unset($list[$key]);
        }
    }
    return $tree;
}

在该函数中传递关联数组,如果最父级不为null,则只需传递最父级id作为第二个参数。

答案 4 :(得分:0)

我遇到了另一个问题,在此页面上找不到适合我的解决方案。我需要创建一棵树,但不知道根ID 。 这意味着我必须遍历平面数组,并在树的顶部建立父项最多的分支。

如果其他人需要构建没有根父项id的树,这就是我的方法。

<?php

$rows = [
    (object) [
        'id' => 1001,
        'parentid' => 1000,
        'name' => 'test1.1'
    ],
    (object) [
        'id' => 1000,
        'parentid' => 100,
        'name' => 'test1'
    ],
    (object) [
        'id' => 1002,
        'parentid' => 1000,
        'name' => 'test1.2'
    ],
    (object) [
        'id' => 1004,
        'parentid' => 1001,
        'name' => 'test1.1.1'
    ],
    (object) [
        'id' => 1005,
        'parentid' => 1004,
        'name' => 'test1.1.1.1'
    ],
    (object) [
        'id' => 100,
        'parentid' => 10,
        'name' => 'test 0'
    ],
    (object) [
        'id' => 1006,
        'parentid' => 1002,
        'name' => 'test1.2.1'
    ],
    (object) [
        'id' => 1007,
        'parentid' => 1002,
        'name' => 'test1.2.2'
    ],
];

function add_child(stdClass $parent, stdClass $child) {
    if ($child->parentid != $parent->id) {
        throw new Exception('Attempting to add child to wrong parent');
    }

    if (empty($parent->children)) {
        $parent->children = [];
    } else {
        // Deal where already in branch.
        foreach ($parent->children as $idx => $chd) {
            if ($chd->id === $child->id) {
                if (empty($chd->children)) {
                    // Go with $child, since $chd has no children.
                    $parent->children[$idx] = $child;
                    return;
                } else {
                    if (empty($child->children)) {
                        // Already has this child with children.
                        // Nothing to do.
                        return;
                    } else {
                        // Both childs have children - merge them.
                        $chd->children += $child->children;
                        $parent->children[$idx] = $child;
                        return;
                    }
                }
            }
        }
    }

    $parent->children[] = $child;
}

function build_branch(&$branch, &$rows, &$parent = null) {
    $hitbottom = false;
    while (!$hitbottom) {
        $foundsomething = false;
        // Pass 1 - find children.
        $removals = []; // Indexes of rows to remove after this loop.
        foreach ($rows as $idx => $row) {
            if ($row->parentid === $branch->id) {
                // Found a child.
                $foundsomething = true;
                // Recurse - find children of this child.
                build_branch($row, $rows, $branch);
                add_child($branch, $row);
                $removals[] = $idx;
            }
        }
        foreach ($removals as $idx) {
            unset($rows[$idx]);
        }
        // Pass 2 - find parents.
        if ($parent === null) {
            $foundparent = false;
            foreach ($rows as $idx => $row) {
                if ($row->id === $branch->parentid) {
                    // Found parent
                    $foundsomething = true;
                    $foundparent = true;

                    add_child($row, $branch);
                    unset ($rows[$idx]);
                    // Now the branch needs to become the parent since parent contains branch.
                    $branch = $row;
                    // No need to search for other parents of this branch.
                    break;
                }
            }
        }

        $hitbottom = !$foundsomething;
    }
}

function build_tree(array $rows) {
    $tree = [];
    while (!empty($rows)) {
        $row = array_shift($rows);
        build_branch($row, $rows);
        $tree[] = $row;
    }
    return $tree;
}

$tree = build_tree($rows);

print_r($tree);