php - 使用 mysql 结果从多维 PHP 数组构建树

标签 php mysql arrays recursion multidimensional-array

我想创建一个函数,以递归方式从具有未知级别和未知元素数量的多维数组生成 TreeView

这是数据库文件

--
-- Table structure for table `accounts_tree`
--

CREATE TABLE `accounts_tree` (
  `id` bigint(20) NOT NULL,
  `parent_id` bigint(20) DEFAULT '0',
  `final_acc_id` bigint(20) NOT NULL,
  `Code` varchar(255) DEFAULT NULL,
  `name_a` varchar(255) DEFAULT NULL,
  `name_e` varchar(255) DEFAULT NULL,
  `nature` tinyint(1) DEFAULT '0',
  `currency_id` bigint(20) NOT NULL DEFAULT '0',
  `currency_rate` varchar(200) DEFAULT NULL,
  `match_date` date DEFAULT NULL,
  `notes` text,
  `created` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `accounts_tree`
--

INSERT INTO `accounts_tree` (`id`, `parent_id`, `final_acc_id`, `Code`, `name_a`, `name_e`, `nature`, `currency_id`, `currency_rate`, `match_date`, `notes`, `created`) VALUES
(1, 0, 1, '1', 'folder 1', 'budget', 0, 1, '1', NULL, NULL, '2017-12-16 00:00:00'),
(2, 0, 1, '1', 'folder 2', 'budget2', 0, 1, '1', NULL, NULL, '2017-12-16 00:00:00'),
(3, 1, 1, '1', 'sub 1-1', 'balance sheet', 0, 1, '1', NULL, NULL, '2017-12-16 00:00:00'),
(4, 2, 1, '1', 'sub 2-1', 'balance sheet', 0, 1, '1', NULL, NULL, '2017-12-16 00:00:00'),
(5, 3, 1, '1', 'Sub 1-1-1', 'balance sheet', 0, 1, '1', NULL, NULL, '2017-12-16 00:00:00'),
(6, 0, 1, '3', 'folder 3', 'balance sheet', 0, 1, '1', NULL, NULL, '2017-12-16 00:00:00'),
(7, 5, 1, '3', 'sub 1-1-1-1', 'balance sheet', 0, 1, '1', NULL, NULL, '2017-12-16 00:00:00');

PHP 生成数组

$query = "SELECT * FROM `accounts_tree`";
$result = $db->query($query);
$output = array();
while ($row = $db->fetch_assoc($result)) {
    $sub_data["id"] = $row["id"];
    $sub_data["name"] = $row["name_a"];
    $sub_data["parent_id"] = $row["parent_id"];
    $data[] = $sub_data;
}
foreach ($data as $key => &$value) {
    $output[$value["id"]] = &$value;
}
foreach ($data as $key => &$value) {
    if ($value["parent_id"] && isset($output[$value["parent_id"]])) {
        $output[$value["parent_id"]]["nodes"][] = &$value;
    }
}
foreach ($data as $key => & $value ) {
    if ($value["parent_id"] && isset($output[$value["parent_id"]])) {
        unset($data[$key]);
    }
}

已编辑

输出数组为

Array
(
    [0] => Array
        (
            [id] => 1,
            [name] => "folder 1",
            [parent_id] => 0,
            [nodes] => Array
                (
                    [0] => Array
                        (
                            [id] => 3,
                            [name] => "sub 1-1",
                            [parent_id] => 1,
                            [nodes] => Array
                                (
                                    [0] => Array
                                        (
                                            [id] => 5,
                                            [name] => "Sub 1-1-1",
                                            [parent_id] => 3,
                                            [nodes] => Array
                                                (
                                                    [0] => Array
                                                        (
                                                            [id] => 7,
                                                            [name] => "sub1-1-1-1",
                                                            [parent_id] => 5
                                                        )

                                                )

                                        )

                                )

                        )

                )

        ),

    [1] => Array
        (
            [id] => 2,
            [name] => "folder 2",
            [parent_id] => 0,
            [nodes] => Array
                (
                    [0] => Array
                        (
                            [id] => 4,
                            [name] => "sub 2-1",
                            [parent_id] => 2
                        )

                )

        ),

    [5] => Array
        (
            [id] => 6,
            [name] => "folder 3",
            [parent_id] => 0
        )
    );

我们只需要收集名称并将其放在 TreeView 中 请任何人都可以解决这个问题:S

谢谢

最佳答案

可以在内嵌注释中找到说明。此功能提供您确切所需的输出。另请注意我重写以设置 $resultset 的查询。

代码:(Demo)

function findParent(&$array,$parentid=0,$childarray=[]){  // make $array modifiable
    foreach($array as $i=>&$row){                         // make $row modifiable
        if($parentid){                                    // if not zero
            if($row['id']==$parentid){                    // found parent
                $row['nodes'][]=$childarray;              // append child to parent's nodes subarray
            }elseif(isset($row['nodes'])){                // go down rabbit hole looking for parent
                findParent($row['nodes'],$parentid,$childarray);  // look deeper for parent while preserving the initial parent_id and row
            }                                             // else continue;
        }elseif($row['parent_id']){                       // child requires adoption
            unset($array[$i]);                            // remove child from level because it will be store elsewhere and won't be its own parent (reduce iterations in next loop & avoid infinite recursion)
            findParent($array,$row['parent_id'],$row);    // look for parent using parent_id while carrying the entire row as the childarray
        }                                                 // else continue;
    }
    return $array;                                        // return the modified array
}


// $db->query('SELECT id,name_a AS name,parent_id FROM accounts_tree ORDER BY id');
// for($resultset=[]; $row=$res->fetch_assoc(); $resultset[]=$row);  // inspired by: http://php.net/manual/en/mysqli-result.fetch-assoc.php#112924

$resultset=[
    ['id'=>1,'name'=>'folder 1','parent_id'=>0],
    ['id'=>2,'name'=>'folder 2','parent_id'=>0],
    ['id'=>3,'name'=>'sub 1-1','parent_id'=>1],
    ['id'=>4,'name'=>'sub 2-1','parent_id'=>2],
    ['id'=>5,'name'=>'Sub 1-1-1','parent_id'=>3],
    ['id'=>6,'name'=>'folder 3','parent_id'=>0],
    ['id'=>7,'name'=>'sub 1-1-1-1','parent_id'=>5]
];

print_r(findParent($resultset));

输出:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => folder 1
            [parent_id] => 0
            [nodes] => Array
                (
                    [0] => Array
                        (
                            [id] => 3
                            [name] => sub 1-1
                            [parent_id] => 1
                            [nodes] => Array
                                (
                                    [0] => Array
                                        (
                                            [id] => 5
                                            [name] => Sub 1-1-1
                                            [parent_id] => 3
                                            [nodes] => Array
                                                (
                                                    [0] => Array
                                                        (
                                                            [id] => 7
                                                            [name] => sub 1-1-1-1
                                                            [parent_id] => 5
                                                        )

                                                )

                                        )

                                )

                        )

                )

        )

    [1] => Array
        (
            [id] => 2
            [name] => folder 2
            [parent_id] => 0
            [nodes] => Array
                (
                    [0] => Array
                        (
                            [id] => 4
                            [name] => sub 2-1
                            [parent_id] => 2
                        )

                )

        )

    [5] => Array
        (
            [id] => 6
            [name] => folder 3
            [parent_id] => 0
        )

)

关于php - 使用 mysql 结果从多维 PHP 数组构建树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47846237/

相关文章:

javascript - 将对象作为 POST 变量从 jquery 传递到 php

php - 使用多行字符串的正则表达式修剪行并缩小空格

mysql - 按帖子数量排序线程

Java 字节移位

arrays - VBA:变体数组与类型数组与非键控集合的迭代速度

javascript - 合并未知数量的不重复的数组

php - Chrome : Google Maps API JS Loading Issue with https

php - 我应该将哪些参数声明为 sql 占位符?

mysql - 删除重复项的查询生成错误

php - 为 HTML 输入字段格式化 MySQL 查询