如何在 Laravel 的 map 方法中使用 array_push?
How to use array_push in map method in Laravel?
$ids = [1];
$collection = collect([2]);
$collection->map(function ($item) use ($ids) {
array_push($ids, $item);
});
dd($ids);
此代码returns
array:1 [
0 => 1
]
我认为这会 return [1, 2]
因为 array_push
;
我怎样才能得到 [1, 2]
或
array:2 [ 0 => 1 1 => 2 ]
?
试试这个:
$ids = [1];
$item_collection = $collection->map(function ($item) {
return $item;
})
->all();
$result = array_push($ids, $item_collection);
这可能适用于您的情况。
我认为您不需要地图函数来执行此操作。
$ids = [1];
$collection = collect($ids);
$item = [2];
$collection = $collection->conact($item);
dd($collection);
/*
Illuminate\Support\Collection {#4937
#items: array:2 [
0 => 1
1 => 2
]
}
*/
或使用合并:
$collection = collect([1]);
$collection = $collection->merge([2]);
dd($collection);
$ids = [1];
$collection = collect([2]);
$collection->map(function ($item) use ($ids) {
array_push($ids, $item);
});
dd($ids);
此代码returns
array:1 [ 0 => 1 ]
我认为这会 return [1, 2]
因为 array_push
;
我怎样才能得到 [1, 2]
或
array:2 [ 0 => 1 1 => 2 ]
?
试试这个:
$ids = [1];
$item_collection = $collection->map(function ($item) {
return $item;
})
->all();
$result = array_push($ids, $item_collection);
这可能适用于您的情况。
我认为您不需要地图函数来执行此操作。
$ids = [1];
$collection = collect($ids);
$item = [2];
$collection = $collection->conact($item);
dd($collection);
/*
Illuminate\Support\Collection {#4937
#items: array:2 [
0 => 1
1 => 2
]
}
*/
或使用合并:
$collection = collect([1]);
$collection = $collection->merge([2]);
dd($collection);