我对集合进行了分组,并使用each()函数对其进行迭代。在每个函数内,我想将元素添加到某个数组中。但它不起作用。有什么想法吗?
$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 版本:8.35.1
您需要使用
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
});
只要
&
不是对象实例,就需要按引用传递 ($dataSet1
)。