laravel将级联数组通过f_id转变成正常数组
时间: 2023-08-16 21:09:46 浏览: 92
可以使用 Laravel 中的 `Collection` 类来将级联数组转换成正常数组。假设你有以下的级联数组:
```php
$data = [
[
'id' => 1,
'name' => 'A',
'f_id' => 0,
'children' => [
[
'id' => 2,
'name' => 'B',
'f_id' => 1,
'children' => [
[
'id' => 3,
'name' => 'C',
'f_id' => 2,
'children' => []
]
]
]
]
],
[
'id' => 4,
'name' => 'D',
'f_id' => 0,
'children' => []
]
];
```
可以使用以下代码将其转换成正常数组:
```php
$collection = collect($data);
$normalized = $collection->flatMap(function ($item) {
return array_merge($item, ['children' => $item['children'] ? $item['children']->pluck('id')->toArray() : []]);
})->toArray();
```
这段代码会将每个子数组中的 `children` 转换成子数组中 `id` 的数组。转换后的结果如下:
```php
[
[
'id' => 1,
'name' => 'A',
'f_id' => 0,
'children' => [2, 3]
],
[
'id' => 2,
'name' => 'B',
'f_id' => 1,
'children' => [3]
],
[
'id' => 3,
'name' => 'C',
'f_id' => 2,
'children' => []
],
[
'id' => 4,
'name' => 'D',
'f_id' => 0,
'children' => []
]
]
```
阅读全文