doushuhuai7247 2011-06-18 19:25
浏览 82
已采纳

php数组分层

i have a table like this:

+----+--------+-------+
| id | parent | title |
+----+--------+-------+
|  1 |   NULL | yek   |
|  2 |   NULL | do    |
|  3 |      1 | se    |
|  4 |      3 | char  |
+----+--------+-------+

and i need to get array of Hierarchical data like this. what is the best way ?

Array
(
    [1] => Array
        (
            [3] => Array
                (
                    [4] => 
                )

        )

    [2] => 
)

please help me.

  • 写回答

3条回答 默认 最新

  • doutang7415 2011-06-18 19:35
    关注
    // dummy data $recordset should be retrieved from db
    $recordset = array(array('id'=>1, 'parent'=>NULL, 'title'=>'yek'),
                       array('id'=>2, 'parent'=>NULL, 'title'=>'do'),
                       array('id'=>3, 'parent'=>1, 'title'=>'se'),
                       array('id'=>4, 'parent'=>3, 'title'=>'char'),
                      );
    
    function make_tree($recordset)
    {
        $tree = array();
        foreach($recordset as $record) {
            if ($record['parent'] !== NULL) {
                if (!array_key_exists($record['parent'], $tree) $tree[$record['parent']] = array('record'=>array(), 'children'=>array());
                $tree[$record['parent']]['children'][$record['id']] = $record;
            } else {
                if (!array_key_exists($record['id'], $tree) $tree[$record['id']] = array('record'=>array(), 'children'=>array());
                $tree[$record['id']] = $record;
            }
        }
    
        return $tree;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算