我有一张这样的 table :

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

我需要获取这样的分层数据数组。什么是最好的方法 ?
Array
(
    [1] => Array
        (
            [3] => Array
                (
                    [4] =>
                )

        )

    [2] =>
)

请帮我。

最佳答案

// 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;
}

关于php数组分层,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6398368/

10-13 21:52