Php 创建子母公司Laravel的无限嵌套层次结构数组
我有一个表Php 创建子母公司Laravel的无限嵌套层次结构数组,php,laravel,sorting,parent-child,Php,Laravel,Sorting,Parent Child,我有一个表company\u basics,它有parent\u id,并且这个子-父关系可以是无限的 目前,我的代码是 $company = \App\CompanyBasic::whereRaw('user_id = ' . Auth::user()->id . " AND parent_id = 0")->get(); // echo "<pre>"; // print_r($company); //
company\u basics
,它有parent\u id
,并且这个子-父关系可以是无限的
目前,我的代码是
$company = \App\CompanyBasic::whereRaw('user_id = ' . Auth::user()->id . " AND parent_id = 0")->get();
// echo "<pre>";
// print_r($company);
// echo "</pre>";
$companies = array();
$count = 0;
foreach($company as $single_company) {
$companies[$count]['id'] = $single_company->id;
$companies[$count]['comp_name'] = $single_company->comp_name;
$child_company = \App\CompanyBasic::whereRaw('user_id = ' . Auth::user()->id . " AND parent_id = '" . $single_company->id . "'")->get();
$child_count = 0;
foreach($child_company as $single_child_company) {
$companies[$count]['child'][$child_count]['id'] = $single_child_company->id;
$companies[$count]['child'][$child_count]['comp_name'] = $single_child_company->comp_name;
$child_count++;
}
echo "company id: " . $single_company->id . "<br>";
$count++;
}
正如@rypskar所建议的,您应该使用递归 我建议您使用将在其中使用自身的方法(称为
closure
),并执行以下操作:
$userId=Auth::user()->id;
$getChildOf=函数($parent)使用($userId,&$getChildOf){
$company=\App\CompanyBasic::whereRaw('user\u id='.$userId.”和parent\u id=“.$parent)->get();
$companies=假;
如果($company->isNotEmpty()){
$companys=array();
foreach($公司作为$单一公司){
$companys[]=数组(
'id'=>$single\u company->id,
“公司名称”=>$single\u company->comp\u name,
“child”=>getChildOf($single_company->id),
);
回显“公司id:”.$single_company->id.
”;
Array
(
[0] => Array
(
[id] => 2
[comp_name] => Habib company
[child] => Array
(
[0] => Array
(
[id] => 16
[comp_name] => Child Company
)
[1] => Array
(
[id] => 18
[comp_name] => Child Company
)
)
)
[1] => Array
(
[id] => 15
[comp_name] => Adjacent Company
)
[2] => Array
(
[id] => 17
[comp_name] => MSB34
)
)
}
}
返回$100公司;
};
$companys=$getChildOf(0);
这里,匿名函数传递给变量$getChildOf
,该变量本身使用
我删除了您的$count
变量以简化代码
顺便说一句,您应该了解,这段代码将在每次迭代中执行数据库查询,因此它将大大增加服务器负载
此外,通过串联将变量注入SQL查询是不安全的,被认为是一种不好的做法。你应该考虑使用你可以查看递归函数。它们可以处理无限深度
$userId = Auth::user()->id;
$getChildOf = function ($parent) use ($userId, &$getChildOf) {
$company = \App\CompanyBasic::whereRaw('user_id = ' . $userId . " AND parent_id = " . $parent)->get();
$companies = false;
if ($company->isNotEmpty()) {
$companies = array();
foreach ($company as $single_company) {
$companies[] = array(
'id' => $single_company->id,
'comp_name' => $single_company->comp_name,
'child' => $getChildOf($single_company->id),
);
echo "company id: " . $single_company->id . "<br>";
}
}
return $companies;
};
$companies = $getChildOf(0);