我有一个marketer表,每个营销商可以有多个营销商,也可以属于一个营销商。我写这个方法是为了检查我是否可以得到一个特定营销人员的多个级别:
表:
id parent_id name
1 NULL a
2 1 b
3 2 c
4 1 d
5 3 e
6 2 f
7 4 g营销者模型:
public function parent()
{
return $this->belongsTo(Self::class);
}
public function children()
{
return $this->hasMany(Self::class,'parent_id');
}方法:
public function marketerWithSubs(Marketer $marketer, $index = 1, $output = [])
{
$output = [];
foreach ($marketer->children as $firstLevel){
$output[1][] = $firstLevel->id . '- ' . $firstLevel->full_name;
foreach ($firstLevel->children as $secondLevel){
$output[2][] = $secondLevel->id . '- ' . $secondLevel->full_name;
foreach ($secondLevel->children as $thirdLevel) {
$output[3][] = $thirdLevel->id . '- ' . $thirdLevel->full_name;
foreach ($thirdLevel->children as $forthLevel) {
$output[4][] = $forthLevel->id . '- ' . $forthLevel->full_name;
foreach ($forthLevel->children as $fifthLevel) {
$output[5][] = $fifthLevel->id . '- ' . $fifthLevel->full_name;
foreach ($firstLevel->children as $sixthLevel) {
$output[6][] = $sixthLevel->id . '- ' . $sixthLevel->full_name;
}
}
}
}
}
}
return $output;
}方法示例输出,这是我所期望的,数组中的索引显示了(所谓的) submarketer的级别,值是一个数组形式的submarketers:
array:6 [▼
1 => array:27 [▶]
2 => array:23 [▶]
3 => array:32 [▶]
4 => array:8 [▶]
5 => array:5 [▼
0 => 102
1 => 63
2 => 64
3 => 65
4 => 67
]
6 => array:35 [▶]
]如何将其转换为实用的方法?
发布于 2021-06-24 17:53:03
好吧,我想我找到答案了:
public function getMarketerWithSubs3(Marketer $marketer, $index = 1, $output = [])
{
foreach ($marketer->children as $firstLevel){
$output[$index][] = $firstLevel->id;
$output = $this->getMarketerWithSubs3($firstLevel, $index+1, $output);
}
return $output;
}发布于 2021-06-24 15:22:22
$output可能必须通过引用传递才能正常工作
public function marketerWithSubs(Marketer $marketer, $index = 1, &$output = [])
{
return array_reduce($marketer->children->all(), function($output, $child) {
$output[$index][] = $child->id . '- ' . $child->full_name;
if ($child->children->count()) {
$this->marketerWithSubs($child, $index++, $output);
}
return $output;
}, $output);
}https://stackoverflow.com/questions/68110652
复制相似问题