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",
]
],
],
]
];
CodePudding user response:
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()
CodePudding user response:
Solution using raw PHP:
$categories = [
[
"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",
],
],
],
];
$children = [];
foreach ($categories as $category) {
$children[] = $category['child']['child'];
}
$categories = $categories[0];
$categories['child']['child'] = $children;
echo "<pre>";
print_r($categories);
die();
// Result
Array
(
[id] => 1
[name] => Root Category
[child] => Array
(
[id] => 2
[name] => Sub category
[child] => Array
(
[0] => Array
(
[id] => 3
[name] => Last level category
)
[1] => Array
(
[id] => 6
[name] => Last level category #2
)
)
)
)