关于php:函数

46次阅读

共计 414 个字符,预计需要花费 2 分钟才能阅读完成。

1. 分类 (当分类只有 2 级的时候这种写好会好点)

$data = [["id" => 1, "name" => "shanghai", "pid" => 0],
            ["id" => 2, "name" => "beijing", "pid" => 0],
            ["id" => 3, "name" => "jiangsu", "pid" => 0],
            ["id" => 4, "name" => "huangpu", "pid" => 1],
            ["id" => 5, "name" => "dongchengqu", "pid" => 2],
            ["id" => 6, "name" => "suzhou", "pid" => 3],
        ];
        $result = [];
        foreach ($data as $value) {$pid = $value['pid'];
            if ($pid > 0) {$result[$pid]['children'] = $value;
            } else {$value['children'] = [];
                $result[$value['id']] = $value;
            }
        }

正文完
 0