您的位置:首页 > 编程语言 > PHP开发

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

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: