layui树形组件需要下列形式的数据。处理数据库数据的时候用到递归,但是有一点点变化。
原数据:
Array
(
[0] => Array
(
[id] => 23
[name] => admin/article/lst
[title] => 文档
[status] => 1
[condition] =>
[type] => 1
[pid] => 0
[show] => 1
)
[1] => Array
(
[id] => 22
[name] => admin/ad/add
[title] => 广告添加
[status] => 1
[condition] =>
[type] => 1
[pid] => 18
[show] => 1
)
[2] => Array
(
[id] => 20
[name] => admin/ad/del/1
[title] => 广告删除1
[status] => 1
[condition] =>
[type] => 1
[pid] => 19
[show] => 1
)
[3] => Array
(
[id] => 19
[name] => admin/ad/del
[title] => 广告删除
[status] => 1
[condition] =>
[type] => 1
[pid] => 18
[show] => 1
)
[4] => Array
(
[id] => 18
[name] => admin/ad/lst
[title] => 广告
[status] => 1
[condition] =>
[type] => 1
[pid] => 0
[show] => 1
)
[5] => Array
(
[id] => 14
[name] => admin/admin
[title] => 管理员
[status] => 0
[condition] =>
[type] => 1
[pid] => 0
[show] => 1
)
[6] => Array
(
[id] => 15
[name] => admin/admin/add
[title] => 管理员添加
[status] => 1
[condition] =>
[type] => 1
[pid] => 14
[show] => 1
)
[7] => Array
(
[id] => 16
[name] => admin/admin/del
[title] => 管理员删除
[status] => 1
[condition] =>
[type] => 1
[pid] => 14
[show] => 1
)
[8] => Array
(
[id] => 24
[name] => admin/article/add
[title] => 文档添加
[status] => 1
[condition] =>
[type] => 1
[pid] => 23
[show] => 1
)
[9] => Array
(
[id] => 25
[name] => admin/article/del
[title] => 文档删除
[status] => 1
[condition] =>
[type] => 1
[pid] => 23
[show] => 1
)
)
php代码:
public function getShu()
{
$rules = self::order('id', 'desc')->select();
$re = $this->_getShu($rules);
return $re;
}
public function _getShu($data, $pid = 0)
{
$t = [];
foreach ($data as $k => $v) {
if ($v['pid'] == $pid) {
$str['title'] = $v['title'];
$str['id'] = $v['id'];
$str['children'] = $this->_getShu($data, $v['id']);
if (empty($str['children'])) {
unset($str['children']);
}
$t[] = $str;
}
}
return $t;
}
处理后得到的数据:
Array
(
[0] => Array
(
[title] => 文档
[id] => 23
[children] => Array
(
[0] => Array
(
[title] => 文档删除
[id] => 25
)
[1] => Array
(
[title] => 文档添加
[id] => 24
)
)
)
[1] => Array
(
[title] => 广告
[id] => 18
[children] => Array
(
[0] => Array
(
[title] => 广告添加
[id] => 22
)
[1] => Array
(
[title] => 广告删除
[id] => 19
[children] => Array
(
[0] => Array
(
[title] => 广告删除1
[id] => 20
)
)
)
)
)
[2] => Array
(
[title] => 管理员
[id] => 14
[children] => Array
(
[0] => Array
(
[title] => 管理员删除
[id] => 16
)
[1] => Array
(
[title] => 管理员添加
[id] => 15
)
)
)
)