PHP 将无限极分类数组 转换为纵向表格
2018-01-11 09:55
375 查看
class Index extends Common { public function test() { $data_list = [ [ 'id' => 1, 'pid' => 0, 'name' => 'A1' ], [ 'id' => 2, 'pid' => 0, 'name' => 'A2' ], [ 'id' => 3, 'pid' => 0, 'name' => 'A3' ], [ 'id' => 4, 'pid' => 3, 'name' => 'A4' ], [ 'id' => 5, 'pid' => 2, 'name' => 'A5' ], [ 'id' => 6, 'pid' => 2, 'name' => 'A6' ], [ 'id' => 7, 'pid' => 0, 'name' => 'A7' ], [ 'id' => 8, 'pid' => 3, 'name' => 'A8' ], [ 'id' => 9, 'pid' => 3, 'name' => 'A9' ], ]; $vertical = $this->data_conversion($data_list); $this->table($vertical); } /** * 数据转换 简陋算法 有空再优化 * @param $data_list * @return array */ public function data_conversion($data_list) { $parents = []; foreach ($data_list as $key => $item) { if ($item['pid'] === 0) { $data = Tree::getChilds($data_list, $item['id']); array_unshift($data, $item); $parents[] = $data; } } $vertical = []; $num = []; foreach ($parents as $key => $parent) { $num[$key] = count($parent); } foreach ($parents as $key => $parent) { $x = max($num) - count($parent); foreach ($parent as $k => $item) { $vertical[$k][$key] = $item; } for ($i = count($parent); $i <= count($parent) + $x - 1; $i ++) { $vertical[$i][$key] = ['name' => '']; } } return $vertical; } /** * 遍历表格 * @param $vertical */ public function table($vertical) { $table = '<br><table border="1" cellspacing="0" cellpadding="0">'; foreach ($vertical as $parent) { $table .= '<tr>'; foreach ($parent as $item) { $table .= '<td>' . $item['name'] . '</td>'; } $table .= '</tr>'; } $table .= '</table><br>'; echo $table; } /** * 获取所有子节点 * @param array $lists 数据集 * @param string $pid 父级id * @return array */ public static function getChilds($lists = [], $pid = '') { $result = []; foreach ($lists as $value) { if ($value[self::$config['pid']] == $pid) { $result[] = $value; $result = array_merge($result, self::getChilds($lists, $value[self::$config['id']])); } } return $result; } }
相关文章推荐
- php 转换无限极分类数组到树状结构
- PHP 无限极分类所形成的三维数组
- 构造无限极分类数组 PHP
- PHP无限极分类之数组
- PHP 无限极分类数组
- php把数据集转换成树状结构,无限极分类生成树状
- PHP数组转换的具体代码编写介绍
- php无限极分类
- php:php多层数组和对象的转换
- php最简单把xml转换成数组的方法
- php将一维数组转换为每3个连续值组成的二维数组
- PHP 数组和字符串互相转换
- php实现xml转换数组的方法示例
- php--------对象(object) 与 数组(array) 的转换
- PHP实现无限极分类
- [PHP] 原生PHP使用递归方式实现数组转换成XML的功能之思考
- php简单对象与数组的转换函数代码(php多层数组和对象的转换)
- PHP数组和Json之间的转换
- PHP XML和数组互相转换
- 用python正则表达式转换php数组到javascript字典