Skip to content
Advertisement

Combine categories tree

I have an array like that:

[
        [
            "id"     => 1,
            "name"   => "Root Category",
            "child"  => [
                "id"    => 2,
                "name"  => "Sub category",
                "child" => [
                    "id"   => 3,
                    "name" => "Last level category",
                ],
            ],
        ],
        [
            "id"     => 1,
            "name"   => "Root Category",
            "child"  => [
                "id"    => 2,
                "name"  => "Sub category",
                "child" => [
                    "id"   => 6,
                    "name" => "Last level category #2",
                ],
            ],
        ],
    ];

In these arrays first level and second level are the same, only the last level is different. I want to combine them into one array. I want to receive result like that:

[
        [
            "id"     => 1,
            "name"   => "Root Category",
            "child"  => [
                "id"    => 2,
                "name"  => "Sub category",
                "child" => [
                    [
                        "id"   => 3,
                        "name" => "Last level category",
                    ],
                    [
                        "id"   => 6,
                        "name" => "Last level category #2",
                    ]
                ],
            ],
        ]
    ];

Advertisement

Answer

collect($arr)
        ->groupBy(function ($item) {
            return $item['id'] . $item['child']['id'];
        })
        ->map(function ($group) {
            $first = $group->first();

            $first['child']['child'] = $group->pluck('child.child')->toArray();

            return $first;
        })
        ->values()
        ->toArray()
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement