我在数据库中有一个表,其中包含组织结构的列:
正如上面的示例数据所示,并非所有级别都有数据,因此有些级别为空。
我想获取所有可能的层次结构组合,因此我使用 GROUP BY
获取数据:
$data = Table::select('group', 'branch', 'unit')->groupBy('group', 'branch', 'unit')->get();
这会以分隔行的形式返回结果。
但是我怎样才能将它变成一个层次结构数组,例如:
[
"g1" => ["b1" => ["other", "u2"]]
"g2" => ["b6" => ["u4"], "other" => ["u3"]]
"g3" => ["b7" => ["other", "u5"]]
]
我替换了null
与 other
在这种情况下以获得更好的引用
最佳答案
我不是 Laravel 开发人员,所以我不能说是否有内置方法可以做到这一点,但一般来说 PHP 并没有那么复杂。
我个人喜欢在事物达到一定程度的复杂性时用对象来支持它们,所以我通常解决这个问题的方法是将 Group、Branch 和 Unit 表示为类,前两个带有子类,然后是主数组保存所有组。我还将对象的“名称”或“标识符”作为索引存储在数组中,以便更轻松地查找内容。那么这只是一个循环的问题。
您可以选择使用组上的 addBranch
方法或类似方法将 isset
逻辑移动到类本身中,但大多数情况下效果是相同的。
Class Unit{
public function __construct(public readonly ?string $name){}
}
Class Branch{
public array $units = [];
public function __construct(public readonly ?string $name){}
}
Class Group{
public array $branches = [];
public function __construct(public readonly string $name){}
}
$sampleData = [
['g1', 'b1', null],
['g1', 'b1', 'u2'],
['g2', null, 'u3'],
['g2', 'b6', 'u4'],
['g3', 'b7', 'u5'],
];
$groups = [];
foreach($sampleData as $row){
$groupId = $row[0];
$branchId = $row[1];
$unitId = $row[2];
if(!isset($groups[$groupId])){
$groups[$groupId] = new Group($groupId);
}
if(!isset($groups[$groupId]->branches[$branchId])){
$groups[$groupId]->branches[$branchId] = new Branch($branchId);
}
if(!isset($groups[$groupId]->branches[$branchId]->units[$unitId])){
$groups[$groupId]->branches[$branchId]->units[$unitId] = new Unit($unitId);
}
}
关于php - 如何将数据库结果集合组织为层次结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74789583/