PHP 将无限极分类数组 转换为纵向表格

2018-01-12 11:16:28来源:网络收集作者:纳米程序员人点击

分享

阿里云爆款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 = '
';
foreach ($vertical as $parent) {
$table .= '';
foreach ($parent as $item) {
$table .= '' . $item['name'] . '';
}
$table .= '';
}
$table .= '
';
echo $table;
}
/**
* 获取所有子节点
* @paramarray $lists 数据集
* @paramstring $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;
}
}

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台