Laravel:array_push 在集合->each() 迭代器中不起作用

问题描述 投票:0回答:1

我对集合进行了分组,并使用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

php laravel collections each array-push
1个回答
6
投票

您需要使用

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
)。

© www.soinside.com 2019 - 2024. All rights reserved.