我有这样一张桌子:
+----+--------+-------+
| 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;
}
标签:sql,php,database
来源: https://codeday.me/bug/20191102/1991939.html