创建 child parent 公司 Laravel 的无限嵌套分层数组

Create unlimited nested hierarchical array of child parent company Laravel

我有一个 table company_basicsparent_id 并且这个 child-parent 关系可以无限。

目前我的密码是

$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++;
}

我只得到 parents 并遍历它们以找到 child 但这是向下一级,但我想向下无限级。

现在返回的代码是

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
        )

)

正如@rypskar 所建议的,您应该使用递归。

我建议你使用 anonymous function,它将在其中使用自身(称为 closure)并执行如下操作:

 $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);

这里匿名函数传递给变量$getChildOf,它自己使用。

我删除了您的 $count 变量以简化代码。

顺便说一句,你应该明白这段代码会在每次迭代时执行一次数据库查询,因此会大大增加服务器负载

此外,将变量注入到 SQL 查询并连接是不安全的,被认为是一种不好的做法。您应该考虑使用 prepared statements