How to add elements to the array using the foreach loop?
$list = [
['User-ID', 'Payout-ID', 'Amount', 'Withdraw address', 'Date'],
];
//generate CSV
foreach ($open_payouts as $open_payout) {
$list .= [
(string)$open_payout->user_id,
(string)$open_payout->id,
(string)number_format($open_payout->amount / 100000000, 8, '.', ''),
(string)$open_payout->user->withdraw_address,
(string)$open_payout->created_at,
];
}
$fp = fopen(app_path() . '/CSV/file.csv', 'w');
//write whole list
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
It seems like my problem is located at $list .=
. How to insert another array into this array, so I can generate a .CSV file from the arrays?
.=
is used to concatenate strings - not arrays.
You simply need to use;
$list[] = [
(string)$open_payout->user_id,
(string)$open_payout->id,
(string)number_format($open_payout->amount / 100000000, 8, '.', ''),
(string)$open_payout->user->withdraw_address,
(string)$open_payout->created_at,
];
That will add your new array onto the end of your $list
array.
You could also use array_push()
;
array_push($list, [
(string)$open_payout->user_id,
(string)$open_payout->id,
(string)number_format($open_payout->amount / 100000000, 8, '.', ''),
(string)$open_payout->user->withdraw_address,
(string)$open_payout->created_at,
]);