[英]Laravel : array_push not working in collection->each() iterator
I have grouped collection and I iterate it using each() function.Inside the each function I want to add element to some array.But it is not working.Any idea?我已经对集合进行了分组,并使用 each() function 对其进行了迭代。在每个 function 中,我想将元素添加到某个数组中。但是它不起作用。知道吗?
$dataSet1 = [];
$appointments = [
['department' => 'finance', 'product' => 'Chair'],
['department' => 'marketing', 'product' => 'Bookcase'],
['department' => 'finance', 'product' => 'Desk'],
];
$groupData = collect($appointments)->groupBy('department');
$groupData->each(function ($item, $key) {
Log::info($key); //Show correct output in log
array_push($dataSet1, $key); //ERROR
array_push($dataSet1, 'A');//ERROR
});
Laravel version: 8.35.1 Laravel 版本:8.35.1
You need to pass the array to the function with use
:您需要将数组传递给 function 并use
:
$groupData->each(function ($item, $key) use (&$dataSet1) {
Log::info($key); //Show correct output in log
array_push($dataSet1, $key); //ERROR
array_push($dataSet1, 'A');//ERROR
});
Pass-by-reference ( &
) is needed as long as $dataSet1
is not an object instance.只要$dataSet1
不是 object 实例,就需要传递引用 ( &
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.