PHP如何在for循环内操作变量并将其返回

时间:2019-04-29 09:48:34

标签: php php-7.2

我已经声明了数组$ data并将其传递给foreach循环的参数。在循环内部,我需要推送或合并新数组并返回它。显然,返回对象不是预期的。它仅包含标题。我正在使用php7.2

$data = ['code','name'];
    $submission->contributions->each(function (Contribution $contribution) use ($data) {

        $rowData = [
            $contribution->employment->employer->code,
            $contribution->employment->employee->last_name,
        ];

        $data = array_merge($data, [$rowData]);
    });
    print_f($data)

1 个答案:

答案 0 :(得分:1)

只需使用foreach,您的$data数组将可用:

$data = ['code','name'];
foreach($submission->contributions as $contribution) {
    $data = array_merge($data, 
        [
            $contribution->employment->employer->code,
            $contribution->employment->employee->last_name
        ]);
}