如何使用foreach循环向元素添加元素?
$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);
}
好像我的问题位于$list .=
。如何在这个数组中插入另一个数组,所以我可以从数组中生成一个.CSV文件?
答案 0 :(得分:1)
.=
用于连接字符串 - 而不是数组。
你只需要使用;
$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,
];
这会将您的新数组添加到$list
数组的末尾。
您也可以使用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,
]);