$result = [
[
"id" => 10,
"father_id" => 2,
"childrens" => [
[
"id" => 54,
"father_id" => 10,
"childrens" => [
[
"id" => 61,
"father_id" => 54,
"childrens" => []
]
]
],
[
"id" => 21,
"father_id" => 10,
"childrens" => []
]
]
]
];
return collect($result)
->map(function ($value) {
return Arr::dot($value); // converts it to the dot notation version (added the example at the end)
})
->collapse() // collapse them into a single one
->filter(function ($value, $key) {
return $key === 'id' || Str::endsWith($key, '.id'); // filter first id + patterns of .id
})
->values() // discard dot notation keys
->toArray();
Arr::dot()
方法将集合转换为以下格式,将所有集合展平为同一级别。
[
{
"id": 10,
"father_id": 2,
"childrens.0.id": 54,
"childrens.0.father_id": 10,
"childrens.0.childrens.0.id": 61,
"childrens.0.childrens.0.father_id": 54,
"childrens.0.childrens.0.childrens": [],
"childrens.1.id": 21,
"childrens.1.father_id": 10,
"childrens.1.childrens": []
}
]
感谢 @Dan 关于已弃用/删除功能的警告array_dot
。替换为Arr::dot()