php - 使用递归函数构建多维数组

标签 php mysql sql arrays recursion

问题:

我正在尝试使用来自 MySQL 的函数和数据构建递归树。然而,结果并不如预期。

PHP代码:

function buildTree($root, $next = array()) 
{
    // Sanitize input
    $root = (int) $root;

    // Do query
    $query = "SELECT CID, Item, Parent FROM betyg_category WHERE Status = '1' AND Parent = '{$root}'";
    $result = mysql_query($query) or die ('Database Error (' . mysql_errno() . ') ' . mysql_error());

    // Loop results
    while ($row = mysql_fetch_assoc($result)) 
    {
      $next[$row['CID']] = array (
                                'CID' => $row['CID'], 
                                'Item' => $row['Item'], 
                                'Parent' => $row['Parent'], 
                                'Children' => buildTree($row['CID'], $next)
                            );
    }

    // Free mysql result resource
    mysql_free_result($result);

    // Return new array
    return $next;
}

$testTree = buildTree(0);

echo "<xmp>".print_r($testTree, true)."</xmp>";

数据库中的表如下所示:

enter image description here

我希望数组是这样的:

Array
(
    [1] => Array
    (
        [CID] => 1
        [Item] => Litteratur
        [Parent] => 0
        [Children] => Array
            (
                [2] => Integration av källorna
                [3] => Belysning av egna resultat
                [4] => Referenser
            )

    )

    and so forth..
)

也就是说,对于每个 parent => 生产 child ,然后转移到下一个 parent ,等等。提前感谢您的任何建议。

最佳答案

这里不需要递归。事实上,它会非常低效,因为您最终会遇到 SELECT N+1 问题。只需按父级排序结果集:

$query = "SELECT CID, Item, Parent FROM betyg_category WHERE Status = '1' ORDER BY Parent";
$result = mysql_query($query);

$tree = array();
while($row = mysql_fetch_assoc($result)) {
    if($row['Parent'] == 0) {
        $row['Children'] = array();
        $tree[$row['CID']] = $row;
    } else {
        $tree[$row['Parent']]['Children'][] = $row;
    }
}

这将产生以下内容:

Array
(
    [1] => Array
        (
            [CID] => 1
            [Item] => Litteratur
            [Parent] => 0
            [Children] => Array
                (
                    [0] => Array
                        (
                            [CID] => 2
                            [Item] => Integration av källorna
                            [Parent] => 1
                        )

                    [1] => Array
                        (
                            [CID] => 3
                            [Item] => Belysning
                            [Parent] => 1
                        )

                    [2] => Array
                        (
                            [CID] => 4
                            [Item] => Referenser
                            [Parent] => 1
                        )

                )

        )

    [5] => Array
        (
            [CID] => 5
            [Item] => Validitet
            [Parent] => 0
            [Children] => Array
                (
                    [0] => Array
                        (
                            [CID] => 6
                            [Item] => Huvudsyfte
                            [Parent] => 5
                        )

                )

        )

)

如果你只想要每个 child 的名字,改变,使用$tree[$row['Parent']]['Children'][] = $row['Item'];反而。

关于php - 使用递归函数构建多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10952041/

相关文章:

php - 简化 MYSQL 查询并修复

mysql - 为什么 MySQL 在 "Error Code: 1054. Unknown column ' 中给我 'on clause' x' 当我在我的 SELECT 中定义它时?

php - 如何使用 PHP 中的过程获取数据?

sql - 比较行并计算同一行的列

mysql - 当一列收到数据时,如何更新列的日期

php - Zend 框架 : How can I add JavaScript element after the scripts in head?

php - Laravel Dusk - 类配置不存在

mysql - 如何对索引表中的所有元素求和

PHP Preg Replace 替换数组

mysql - 通过重复记录选择多于记录数的记录